6

I have a web service that contains one method:

[WebMethod]
public string Movies()
{
    using (var dataContext = new MovieCollectionDataContext())
    {
        var query = dataContext.Movies.Select(m =>new{m.Title,m.ReleaseDate}).Take(20);
        var serializer = new JavaScriptSerializer();
        return serializer.Serialize(query);
    }
}

The method properly serializes the object, but when I view the response in FireBug, it looks like this:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"Title":"SQL","ReleaseDate":"\/Date(1224007200000)\/"},{"Title":"Termonator Salvation","ReleaseDate":"\/Date(1224007200000)\/"}]</string>

Here is jQuery method in which I use Kendo Data Source

$(function () {
    alert("Welcome To Kendo");
    var dataSource = new kendo.data.DataSource(
                {
                    transport: {
                        read: {
                            type: "POST",
                            dataType: "json",
                            url: "/MovieService.asmx/Movies"
                           // contentType: "application/json; charset=utf-8"

                        }
                    },
                    change: function (e) {
                        alert(e);

                    },
                    error: function (e) {
                        alert(e[2]);
                    },
                    pageSize: 10,
                    schema: {
                        data: "d"

                    }


                });

    $("#MovieGridView").kendoGrid({
        dataSource: dataSource,
        height: 250,
        scrollable: true,
        sortable: true,
        pageable: true,
        columns: [
            { field: "Title", title: "Movie Name" },
            { field: "ReleaseDate", title: "Movie Release" }
            ],
        editable: "popup",
        toolbar: ["create"]
    });
});

The above code show what I am doing in jQuery and when the error event call I got this error

SyntaxError: JSON.parse: unexpected character

How can I convert the above data into JSON so I can use it in jQuery? And where am I going wrong?

4

1 回答 1

8

您需要指定ResponseFormat方法的:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMovies() {
}

注意:为了其他遇到类似问题的人,同样重要的是要注意您应该使用POST请求,而不是GET请求。请参阅:JSON 劫持和 ASP.NET AJAX 1.0 如何避免这些攻击


编辑

根据您发布的 jQuery,您没有调用正确的方法。您的 C# 定义了一个名为 的方法GetMovies,但您的 jQuery 试图调用一个名为“Movies”的方法。

这个:

url: "/MovieService.asmx/Movies"

应该改成这样:

url: "/MovieService.asmx/GetMovies"
于 2012-03-28T20:04:49.930 回答