This is a migrated thread and some comments may be shown as answers.

Kendo Grid Insert Record Using WCF with JSONP

1 Answer 118 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Haseeb
Top achievements
Rank 1
Haseeb asked on 16 Apr 2012, 10:47 PM
i have a WCF service and i configure it on jsonp

My Model is MoviesItem

    [DataContract]
    public class MoviesItem
    {
        [DataMember]
        public int MovieID { get; set; }
        [DataMember]
        public string MovieTitle { get; set; }
        [DataMember]
        public DateTime MovieReleseDate { get; set; }
    }


my Service Contract is IMovieService

    [ServiceContract]
    public interface IMoviesService
    {
        [WebGet( BodyStyle = WebMessageBodyStyle.Bare ,RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        IEnumerable<MoviesItem> GetMovies();
    
        [WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        void AddMovies(MoviesItem movies);
    
    }


and my service is called MoviesService

    [AspNetCompatibilityRequirements(RequirementsMode =
        AspNetCompatibilityRequirementsMode.Allowed)]
    public class MoviesService : IMoviesService
    {
    
        public IEnumerable<MoviesItem> GetMovies()
        {
            using (var context = new MovieCollectionDataContext())
            {
                return context.Movies.Select(e => new MoviesItem()
                {
                    MovieID = e.ID,
                    MovieTitle = e.Title,
                    MovieReleseDate = e.ReleaseDate
    
                }).Take(100).ToList();
            }
        }
    
    
        public void AddMovies(MoviesItem movies)
        {
            using (var context = new MovieCollectionDataContext())
            {
    
                var movie = new Movie()
                {
                    Title = movies.MovieTitle,
                    ReleaseDate = DateTime.Now
                };
                context.Movies.InsertOnSubmit(movie);
                context.SubmitChanges();
    
                //return context.Movies.Select(e => new MoviesItem()
                //{
                //    MovieID = e.ID,
                //    MovieTitle = e.Title,
                //    MovieReleseDate = e.ReleaseDate
    
                //}).Take(100).ToList();
    
            }
        }
    }


My Web.config file is:

    <?xml version="1.0"?>
    <configuration>
      <connectionStrings>
        <add name="moviereviewsConnectionString" connectionString="Data Source=Haseeb-PC;Initial Catalog=moviereviews;Integrated Security=True"
          providerName="System.Data.SqlClient" />
      </connectionStrings>
      <system.web>
        <compilation debug="false" targetFramework="4.0">
          <assemblies>
            <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
          </assemblies>
        </compilation>
      </system.web>
      <system.serviceModel>
        <bindings>
          <webHttpBinding>
            <binding name="WebHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"/>
          </webHttpBinding>
        </bindings>
        <behaviors>
          <endpointBehaviors>
            <behavior name="webHttpBehavior">
              <webHttp helpEnabled="true"/>
            </behavior>
          </endpointBehaviors>
          <serviceBehaviors>
            <behavior>
              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
              <serviceMetadata httpGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
        <services>
          <service  name="MoviesService">
            <endpoint address="" behaviorConfiguration="webHttpBehavior"
                      binding="webHttpBinding" bindingConfiguration="WebHttpBindingWithJsonP" contract="IMoviesService"/>
          </service>
        </services>
      </system.serviceModel>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
      </system.webServer>
    </configuration>


nad at last My javascript code code which is used to bind Kendo Grid

    $(function () {
        BindGridWithKendoDataSource();
    });

    function BindGridWithKendoDataSource() {
        var dataSource1 = new kendo.data.DataSource(
            {
                transport:
                    {
                        read:
                            {
                                url: "MoviesService.svc/GetMovies",
                                dataType: "jsonp",
                                //contentType:"application/javascript",
                                type: "GET"
    
    
                            },
                        create:
                            {
                                url: "MoviesService.svc/AddMovies",
                                dataType: "jsonp",
                                contentType: "application/javascript",
                                type: "POST"
                            }
                    },
                parameterMap: function (data, operation) {
                    if (operation !== "read") {
                        return JSON.stringify({ movies: data.models });
                    }
                },
                batch: true,
                pageSize: 10,
                schema:
                    {
                        //data: "d",
                        model:
                            {
                                id: "MovieID",
                                fields:
                                    {
                                        MovieID: { editable: false, nullable: true },
                                        MovieTitle: { validation: { required: true} }
                                        // MovieReleaseDate: {type:"date", editable: true, validation: { required: true} }
                                    }
                            }
                    }
            });
        $("#MoviesGridView").kendoGrid(
            {
                dataSource: dataSource1,
                pageable: true,
                sortable: true,
                filterable: true,
                scrollable: true,
                height: 400,
                toolbar: ["create", "save", "cancel"],
                editable: "popup",
                columns:
                   [
                       { field: "MovieTitle", title: "Movie Title" },
                //{ field: "MovieReleaseDate", title: "Release Date" },
                       {command: ["edit", "destroy"], title: "&nbsp;", width: "210px" }
                       ]
    
            });
    }



my kendo grid is successfully bind from the data return from WCF  in jsonp format but when i click try to innsert the record in the database using Kendo grid i always get error that is:

    "NetworkError: 400 Bad Request - http://localhost:2382/KendoUiTest/MoviesService.svc/AddMovies?callback=jQuery17102623996303075524_1334611809600"


please some one help me to solve this issue that how can i insert the record using WCF. where i am doing wrong i am not able to understand.

1 Answer, 1 is accepted

Sort by
0
Haseeb
Top achievements
Rank 1
answered on 17 Apr 2012, 09:07 PM
i have post my solution which i figured out

JSONP doesn't accept POST request that the main problem
the solution is to make correct the create function and Parameter map function like that

    
    var dataSource1 = new kendo.data.DataSource(
            {
                transport:
                    {
                        read:
                            {
                                url: "MoviesService.svc/GetMovies",
                                dataType: "jsonp",
                                //contentType:"application/javascript",
                                type: "GET"
    
    
                            },
                        create:
                            {
                                url: "MoviesService.svc/AddMovies",
                                dataType: "jsonp",
                                contentType: "application/javascript",
                                type: "POST"
                            },
    parameterMap: function (data, operation) {
                        if (operation != "read") {
                            return { jsonData: kendo.stringify(data.models) };
                        }
                    }
                    },
               
                }, and so on ............

Now change in Contract and Service fuction like that

IMovieService


    [WebGet(ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        void AddMovies(string jsonData);

Now MoviesService Class Will have Above function implementation

    public IEnumerable<MoviesItem> AddMovies(string jsonData)
        {
            using (var context = new MovieCollectionDataContext())
            {
    
                var movies = JArray.Parse(jsonData);
                foreach (var item in movies)
                {
                    var movie = new Movie()
                    {
                        Title = item["MovieTitle"].ToString(),
                        ReleaseDate = DateTime.Parse(item["MovieReleseDate"].ToString())
                    };
                    context.Movies.InsertOnSubmit(movie);
                    context.SubmitChanges();
                }
    
    
                return context.Movies.Select(e => new MoviesItem()
                {
                    MovieID = e.ID,
                    MovieTitle = e.Title,
                    MovieReleseDate = e.ReleaseDate
    
                }).Take(50).ToList();
    
            }
        }


now enjoy WCF with JSONP and also With Kendo........ Its Wonderful


Tags
Grid
Asked by
Haseeb
Top achievements
Rank 1
Answers by
Haseeb
Top achievements
Rank 1
Share this question
or