1

我有一个 WCF 服务,我在 jsonp 上配置它

我的模型是 MoviesItem

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

我的服务合同是 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);

}

我的服务叫做 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();

        }
    }
}

我的 Web.config 文件是:

<?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>

最后我的javascript代码代码用于绑定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" }
                   ]

        });
}

我的剑道网格已从 WCF 以 jsonp 格式返回的数据成功绑定,但是当我单击尝试使用剑道网格在数据库中插入记录时,我总是收到错误消息:

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

请有人帮我解决这个问题,我如何使用 WCF 插入记录。我做错了什么我无法理解。

4

1 回答 1

1

我已经发布了我想出的解决方案

JSONP 不接受 POST 请求,解决的主要问题是像这样正确地创建函数和参数映射函数

var dataSource1 = new kendo.data.DataSource(
        {
            transport:
                {
                    read:
                        {
                            url: "MoviesService.svc/GetMovies",
                            dataType: "jsonp",

                            },
                    create:
                        {
                            url: "MoviesService.svc/AddMovies",
                            dataType: "jsonp",
                                                        },
parameterMap: function (data, operation) {
                    if (operation != "read") {
                        return { jsonData: kendo.stringify(data.models) };
                    }
                }
                },

            }, and so on ............

现在像这样改变合同和服务功能

IMovieService

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

现在 MoviesService 类将具有上述功能实现

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();

        }
    }

现在享受带有 JSONP 和 Kendo 的 WCF........ 太棒了

于 2012-04-17T19:58:48.017 回答