JQGrid-无法调用ASP.NET WebMethod,但可以使用Ajax [英] JQGrid - Cannot call ASP.NET WebMethod but can with Ajax

查看:68
本文介绍了JQGrid-无法调用ASP.NET WebMethod,但可以使用Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jqGrid的新手,但发现很难遵循文档 jqGrid文档

I am new to jqGrid and I have found it difficult to follow the documentation jqGrid Documentation

设置JQGrid时,我不知道如何调用WebMethod.我成功进行了Ajax调用以获取数据,然后使用本地数据设置JQGrid.我认为这是设置过程中的一个额外步骤,我应该能够使用url属性提供webmethod的路径.

I cannot figure out how to call a WebMethod when setting up the JQGrid. I have been successful in making an Ajax call to get the data and then setting up the JQGrid with local data. I think its an extra step in the setup process and that I should be able to provide the path to the webmethod using the url property.

editurl属性是相同的方式.我从未真正收到过发到服务器的帖子.

The editurl property is the same way. I am never actually receiving the post to the server.

原始代码

尝试了JQGrid设置


function GetData()
{
    $('#list').jqGrid({
        type: "POST",
        url: "Default.aspx/GetUsersJSON",
        datatype: "json",
        height: 250,
        colName: ['Username', 'Email'],
        colModel: [
                ...
    }).jqGrid(
                'navGrid',
                '#pager',
                {
                    edit: true,
                    add: true,
                    del: true
                });
}

WebMethod



        [WebMethod]
        public static string GetUsersJSON()
        {
            var users = new List();
            using(UserAdministrationSandboxDataContext uasd = new UserAdministrationSandboxDataContext())
            {
                users = uasd.GetUserList();                
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(users); 

        }

当前代码

我现在让它正常工作,但是我还有最后一个问题.为什么必须设置"repeatitems:false"才能显示内容?

I got it working correctly now, but I still have one final question. Why did I have to set the 'repeatitems: false' in order to display the content?

一些需要注意的事项包括设置ajax请求的不同方法.

Some of the caveats to get this to work include the different ways to setup the ajax request.

(Ajax:type)是(jqgrid:mtype) (Ajax:contentType)是(jqgrid:ajaxGridOptions:{contentType:})

(Ajax: type) is (jqgrid : mtype) (Ajax: contentType) is (jqgrid : ajaxGridOptions: { contentType: })

最后从文档中了解如何设置JSONReader的文档.

And finally understanding the documentation from the documentation on how to setup the JSONReader.

希望这对其他人有帮助,并感谢Oleg的所有帮助.

Hope this helps others and thanks Oleg for all your help.

JS



function GetUserDataFromServer()
{
    $('#list').jqGrid({
        url: "Default.aspx/GetUsersJSON",
        mtype: 'POST',        
        ajaxGridOptions: { contentType: "application/json" },
        datatype: "json",
        serializeGridData: function (postData)
        {
            return JSON.stringify(postData);
        },
        jsonReader: {
            root: function (obj) { return obj.d; },
            page: function (obj) { return 1; },
            total: function (obj) { return 1; },
            records: function (obj) { return obj.d.length; },
            id:'0',
            cell:'',
            repeatitems: false            
        },
        datatype: "json",
        height: 250,
        colName: ['Username', 'Email'],
        colModel: [
                {
                    name: 'Username',
                    index: 'Username',
                    width: 100,
                    editable: true
                },
                {
                    name: 'Email',
                    index: 'Email',
                    width: 220,
                    editable: true
                },
                {
                    name: 'IsLockedOut',
                    index: 'IsLockedOut',
                    width: 100,
                    editable: true,
                    edittype: 'checkbox'
                }
        ],
        caption: "Users"
    })
}

网络方法


        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List GetUsersJSON()
        {
            using (UserAdministrationSandboxDataContext uasd = new UserAdministrationSandboxDataContext())
            {
                return uasd.GetUserList();
            }
        }

列表中的一个JSON对象


{"__type":"UserAdministrationSandbox.UserData","PKID":"00000000-0000-0000-0000-000000000001","Username":"TestUser","ApplicationName":"Test","Email":"TestUser@test.com","Comment":"TestUser","Password":"D41D8CD98F00B204E9800998ECF8427E","PasswordQuestion":"Is this a blank Password?","PasswordAnswer":null,"IsApproved":true,"LastActivityDate":"\/Date(1298869200000)\/","LastLoginDate":"\/Date(1298869200000)\/","LastPasswordChangedDate":"\/Date(1298869200000)\/","CreationDate":"\/Date(1298869200000)\/","IsOnLine":false,"IsLockedOut":false,"LastLockedOutDate":"\/Date(1298869200000)\/","FailedPasswordAttemptCount":0,"FailedPasswordAttemptWindowStart":null,"FailedPasswordAnswerAttemptCount":null,"FailedPasswordAnswerAttemptWindowStart":null}

推荐答案

首先,我希望此答案).主要思想是,您应该使用以下其他jqGrid参数

First of all I hope the code examples from the answer could help you (see also this answer). The main idea, that you should use following additional jqGrid parameters

ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
    return JSON.stringify(postData);
},
jsonReader: { root: "d.rows", page: "d.page", total: "d.total",
              records: "d.records" };

如果服务器未在响应中设置rowspagetotalrecords参数,并且仅返回数据列表(如您的情况),则可以使用以下jsonReader

If the server not set rows, page, total and records parameter in the response and just return the list of data like in your case you can use the following jsonReader

jsonReader: {
    root: function (obj) { return obj.d; },
    page: function (obj) { return 1; },
    total: function (obj) { return 1; },
    records: function (obj) { return obj.d.length; }
}

(请参见此处此处).如果您不想实现服务器端数据分页,排序和过滤,我建议您使用loadonce:true.

(see here and here). In the case if you don't want implement server side data paging, sorting and filtering I recommend you to use loadonce:true.

此外,您的代码有一些问题.第一个是您在Web方法中手动调用JavaScriptSerializer.Serialize.如果使用dataType: "json",则JSON响应将由$.ajax转换为object.您的情况也是如此.因此,success处理程序的msg参数具有d属性.但是msg.d不是对象,而是一个另外的JSON字符串,您可以使用eval(msg.d)将该字符串转换为对象.原因是方法的结果将再次转换为JSON.

Moreover your code have some problems. The first one is that you call JavaScriptSerializer.Serialize manually in your web method. If you use dataType: "json" the JSON response will be converted to object by $.ajax. It is so in your case also. Because of that the msg parameter of the success handler has d property. But msg.d is not the object, but one more JSON string which you convert to object with eval(msg.d). The reason is that the results of your method will be converted to JSON one more time.

要解决此问题,您应该将网络方法GetUsersJSON更改为以下内容:

To fix the problem you should change the web method GetUsersJSON to the following:

[WebMethod]
[ScriptMethod (ResponseFormat = ResponseFormat.Json)]
public static List<User> GetUsersJSON()
{
    using(UserAdministrationSandboxDataContext uasd =
                                    new UserAdministrationSandboxDataContext())
    {
        return uasd.GetUserList();                
    }
}

然后您可以将上一个示例中的data: eval(msg.d)放置到data: msg.d.

then you can place data: eval(msg.d) in your previous example to data: msg.d.

通常情况下,对于Web方法,可以使用附加的[ScriptMethod (ResponseFormat = ResponseFormat.Json)][ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]属性,但是在很多情况下(在您的情况下似乎也是如此)是不需要的.

Typically one use additional [ScriptMethod (ResponseFormat = ResponseFormat.Json)] or [ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] attribute for the web method, but in many cases (it seems also in your case) it is not needed.

使用ajaxGridOptionsserializeGridDatajsonReader后,jqGrid将能够读取数据页面,但是数据应为JSON格式,而不是两次编码的JSON格式.

After the usage of ajaxGridOptions, serializeGridData and jsonReader jqGrid will able to read the page of data, but the data should be in JSON format and not twice encoded JSON format.

更新:您要求我发表评论为什么,您需要使用jsonReader中的repeatitems:false设置才能读取您的数据.对于理解jsonReader的工作方式来说,这是一个重要的问题,但是答案将占很小的位置.

UPDATED: You ask me to comment why you need to use repeatitems:false setting in the jsonReader to be able to read your data. It is important question for understanding how jsonReader work, but the answer will take a little place.

通常,有两种主要样式可用于为jqGrid格式化JSON数据.它应该是网格行的数据数组.数组的每一项都代表网格中的行,并且该行应为两个主要形式中的一个.

In general there are two main styles how the JSON data can be formatted for jqGrid. It should be array of data for grid rows. Every item of the array represent the row in grid and the row should be in one from the two main form

1)作为具有类似命名属性的对象

1) as an object with named properties like

{"Username":"TestUser","Email":"TestUser@test.com","Comment":"..","IsApproved":true}

或2)像这样的字符串数组

or 2) an array of strings like

["TestUser","TestUser@test.com","true"]

["TestUser","TestUser@test.com","1"]

jqGrid在edittype:'checkbox'设置的情况下将"true"和"1"值都映射为布尔值"true".如何了解网格中是否有很多复选框列,使用"1"/"0"格式可以减小传输数据的大小.

jqGrid map both "true" and "1" values to the boolean value "true" in case of edittype:'checkbox' setting. How you can understand if the grid has many checkbox-columns the usage of "1"/"0" format can reduce the size of transfered data.

repeatitems:false选项意味着jqGrid应该扫描JSON数据以查找数据的第一个(对象样式)表示形式. repeatitems:true表示第二个(数组样式)表示形式.

The repeatitems:false option means that jqGrid should scan JSON data for the first (object style) representation of data. The repeatitems:true means the second (array style) representation.

如果使用对象样式(repeatitems:false),则jsonReadercell设置将不使用,并且可以删除使用的cell:''设置.

By the way if you use the object style (repeatitems:false) the cell setting of the jsonReader will be not used and you can remove cell:'' setting which you use.

如果网格中的一列具有唯一值,则jsonReaderid选项是数字形式的实用方法.选项id:'0'表示用户名"列的值将用作行ID.如果使用IE或Chrome开发人员工具的Firebug检查网格,则会看到相应的<tr>元素具有属性id="TestUser"(用于数据中).因为在一个HTML页面上不允许在ID中重复ID,所以您可以理解,使用正确的唯一ID定义网格非常重要.如果jqGrid在数据中找不到ID列,它将使用ID"1","2",....因此,如果看到网格具有值,则应在jsonReaderid属性中搜索错误. >.

The id option of the jsonReader in numeric form is practical if you have one column in the grid with unique values. The option id:'0' means that the value of the column "Username" will be used as the row id. If you examine the grid with Firebug of Developer tools of IE or Chrome you will see that the corresponding <tr> element has attribute id="TestUser" (used in your data). Because duplicate in ids are not allowed on one HTML page, you can understand that it is very important to define grid with correct unique ids. If jqGrid not find id column in the data it will use ids "1", "2", ... So if you see that your grid has the values you should search for the error in the id property of the jsonReader.

下一个重要的事情是两种数据表示方式的优缺点:对象样式(repeatitems:false)和数组样式(repeatitems:true)

The next important thing is the advantages and disadvantages of two ways of the data representation: object style (repeatitems:false) and array style (repeatitems:true)

对象样式在两种主要情况下具有优势

The object style has advantage in two main cases

  1. 您只想在服务器上发布较少工作的现有对象(快速而肮脏的解决方案)
  2. 您从服务器获取无法更改的接口数据.

在所有其他情况下,数组样式(repeatitems:true)与对象样式相比具有优势.来自那里的主要

In all other situations the array style (repeatitems:true) has advantages compared with the object style. The main from there

  1. 在对象样式表示中,将经常根据需要发送更多数据.在您的示例中,将发送评论"属性,而jqGrid将不使用该属性.
  2. 数组样式的数据更加紧凑,因为您不会在每一行中传输属性名称(常量).
  1. In the object style representation will be send frequently more data as needed. In your example the "Comment" property for example will be send which will not be used by jqGrid.
  2. The data from array style are much more compacter because you will not transfer the name of properties (which are constants) in every row.

因此,如果您想减小传输数据的大小,并且可以在服务器端进行更改,我建议您使用数据表示形式的数组样式(repeatitems:true).在这种情况下,可以很好地使用jsonReadercell:''属性.

So if you want to reduce the size of transfered data and you can make changes on the server side I would recommend you to use array style (repeatitems:true) of representation of data. In the case the cell:'' property of the jsonReader can be good used.

我建议您仔细阅读 jqGrid文档的一部分jsonReader,xmlReaderlocalReader的a>.

I recommend you to look though the part of jqGrid documentation about jsonReader, xmlReader and localReader.

这篇关于JQGrid-无法调用ASP.NET WebMethod,但可以使用Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆