Problem binding jqGrid in ASP.NET

2019-02-21 03:25发布

问题:

I am new to using jqGrid and jquery.I am not able to bind my json data which I retrive from the webmethod onto the jqGrid.

I have also used firebug to cross verify and i am receiving data from it. Some help regarding this will be great. I would aslo like to know if any other references needs to be added.

following is the code that I have implemented.

PAGE METHOD

[WebMethod]
public static string GetData()
{
    Customer Cone = new Customer();
    Customer Ctwo = new Customer();
    Cone.CustomerID = "100";
    Cone.CustomerName = "abc";
    Ctwo.CustomerID = "101";
    Ctwo.CustomerName = "xyz";
    List<Customer> lstCustomer = new List<Customer>();
    lstCustomer.Add(Ctwo);
    lstCustomer.Add(Cone);
    JavaScriptSerializer jsonSerz = new JavaScriptSerializer();
    string serializedData = jsonSerz.Serialize(lstCustomer);
    return serializedData; 
}

client side coding

<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery.jqGrid.min.js"></script>
<script type="text/javascript">
    function GetData() {
        alert('Inside GetData');
        var data = PageMethods.GetData(OnSuccess, OnFailed);
    }
    function OnFailed(error) {
        alert('Failed');
        alert(error.get_message());
    }
    function OnSuccess(data) {
            alert(data);
    }
    $(document).ready(function() {
        $('#submit').click(function() {
            alert('Button Clicked');
            $('#list').jqGrid({
                url: 'http://localhost:1405/WebSite1/Default.aspx/GetData',
                data: '{}',  // For empty input data use "{}",
                dataType: 'local',
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                colNames: ['CustomerID', 'CustomerName'],
                colModel: [
                    { name: 'CustomerID', index: 'CustomerID', width: 80,
                      align: 'left', editable: false },
                    { name: 'CustomerName', index: 'CustomerName', width: 120,
                      align: 'left', editable: true}],
                pager: $('#pager'),
                rowNum: 5,
                rowList: [10],
                sortname: 'CustomerID',
                sortorder: 'desc',
                viewrecords: true,
                width: 300
            });
        });
    });
</script>

AND HTML code

<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<input type="button" id="submit" value="Fetch" title="Fetch"
       onclick="javascript:GetData()" />
<table id="list">
</table>
<div id="pager">   
</div>

回答1:

First of all I recommend you to play a little with another working code which you can download here (see more information here). More links to another examples you can find here.

I try to describe some problems in your current code.

  1. You use 'http://localhost:1405/WebSite1/Default.aspx/GetData' as the url. You shold better use only pathes like '/WebSite1/Default.aspx/GetData' or 'WebSite1/Default.aspx/GetData' or you can easy receive same origin policy problem.
  2. You should use ASMX service instead of placing the code inside of ASPX page (Default.aspx/GetData). You should just add new item to your ASP.NET solution and choose Web Serice template. The corresponding code template will be added for you and web.config will be modified. In the same way you can place WCF service inside your ASP.NET project. The step is independ on the technology which you use (WebForms, ASP.NET MVC and so on).
  3. Instead of manual JSON serialisation with respect of JavaScriptSerializer you should define [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attriute to your method and return an object from the web method (like List<Customer> in your case). The JSON serialization will be done automatically for you.
  4. You use dataType: 'local' which is wrong parameter for jqGrid. Correct parameter will be datatype:'json' (datatype instead of dataType and 'json' to make the request to the server).
  5. Instead of type: 'POST' you should use mtype: 'POST'.
  6. Instead of contentType: "application/json; charset=utf-8" you should use ajaxGridOptions: { contentType: "application/json" }.
  7. The usage of data: '{}' is also wrong. Probably you try to use data parameter of jQuery.ajax like with dataType parameter. In jqGrid you should use pastData instead of data and the data parameter must be an array and has another meaning. I recommand you to look at the code of the example (see reference at the begin of my answer).
  8. You should not place $('#list').jqGrid({...}); inside of click handle. The problem is that the code make some initializations of jqgrid and then fill the grid. What you probaly want is creating the grid only once and then refreshing it with another input data probaby (I am not sure that it is so). So you should move $('#list').jqGrid({...}); inside of $(document).ready(function() {...};. If needed you can use $('#list').trigger("reloadGrid") inside of the click event handle. Alternatively you can use GridUnload to destroy the existing grid before creating it new.

I can continue, but my main recommendation is to examine another examples and use ASMX or WCF service which provide the data for jqGrid.



回答2:

Entire grid binding event is called before your page method. You have put it under document.Ready event. Try calling it from the button click event.

I am not sure but there should be some way to bind json data to Jquery grid on client side without using the URL part.

try mapping "data:" to some Json value.