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コードコード

$(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" }
                   ]

        });
}

私の剣道グリッドは、jsonp 形式の WCF から返されたデータから正常にバインドされますが、クリックすると、剣道グリッドを使用してデータベースにレコードを挿入しようとすると、常に次のエラーが発生します。

"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 で WCF を楽しんでいますし、剣道も一緒に楽しんでいます....その素晴らしい

于 2012-04-17T19:58:48.017 に答える