asp.net web forms [WebMethod]



当我使用Entity FrameworkDB返回Json数据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;
    }

更多内容请阅读

相关内容

  • 没有找到相关文章

最新更新