asp.net 网络表单 [WebMethod]

asp.net web forms [WebMethod]

当我使用 Entity Framework

return Json 来自 DB 的数据 List<Contract> 时,我的 [WebMethod] 出现问题
function populateData(pageIndex) {
                // populate data from database
                $.ajax({
                    url: "/Pages/App/Docs.aspx/PopulateDataByJquery",
                    data: "{pageNo: " + pageIndex + ", noOfRecord: 7}",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: OnSuccess,
                    error: onError
                });
            }
            function OnSuccess(data) {

                alert('good');
            }
            function onError() {
                alert('Failed!');
                $('#LoadingPanel').css('display', 'none');
            }

这是我的 WeMethod。

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static List<Contract> PopulateDataByJquery(int pageNo, int noOfRecord)
    {
        System.Threading.Thread.Sleep(2000);
        Entities4 db = new Entities4();
        List<Contract> data = new List<Contract>();
        int skip = (pageNo - 1) * noOfRecord;
        data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList(); 
        return data;
    }

我每次都出现ajax错误,请帮帮我!不知道怎么解决的

您必须对 ajax 调用和 WebMethod

进行一些更改
function populateData(pageIndex) {
                    // populate data from database
                    $.ajax({
                        url: "Docs.aspx/PopulateDataByJquery",
                        data: "{pageNo: pageIndex, noOfRecord: 7}",
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: OnSuccess,
                        error: onError
                    });
                }
                function OnSuccess(data) {

                    alert('good');
                }
                function onError() {
                    alert('Failed!');
                    $('#LoadingPanel').css('display', 'none');
                }

改变你的WebMethod

    [WebMethod]
    public static string  PopulateDataByJquery(int pageNo, int noOfRecord)
    {
        System.Threading.Thread.Sleep(2000);
        Entities4 db = new Entities4();
        List<Contract> data = new List<Contract>();
        int skip = (pageNo - 1) * noOfRecord;
        data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList(); 
        JavaScriptSerializer TheSerializer = new JavaScriptSerializer()
        var TheJson = TheSerializer.Serialize(data);
         // for this you need to add using System.Web.Script.Serialization;
        return TheJson;
    }

阅读更多this