【问题标题】:Load data from Webservice (asmx) to jqgrid. Please help me将数据从 Webservice (asmx) 加载到 jqgrid。请帮我
【发布时间】:2011-05-01 02:29:04
【问题描述】:

我创建了一个 Sample 来测试 jqgrid。

GetDataService.asmx:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace ExampleJqGrid
{
    /// <summary>
    /// Summary description for GetDataService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class GetDataService : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetProduct()
        {
            SqlConnection con = new SqlConnection(@"Data Source=NGUYEN-LAPTOP\SQLEXPRESS;Initial Catalog=ProductDB;Integrated Security=True");
            //SqlCommand cmd = new SqlCommand("SELECT * FROM Products", con);
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Products", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataTable dt = ds.Tables[0];            
            GetJSONFromDataTable getJsonDataTable = new GetJSONFromDataTable();
            string json = getJsonDataTable.GetJSONString(dt);
            string jonsData = GetJSONFromDataTable.JsonForJqgrid(dt, 10, 10, 2);
            return jonsData;
        }
    }
}

GetJSONFromDataTable.cs

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace ExampleJqGrid
{
    public class GetJSONFromDataTable
    {public static string JsonForJqgrid(DataTable dt, int pageSize, int totalRecords,int page) 
         {
             int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
             StringBuilder jsonBuilder = new StringBuilder();
             jsonBuilder.Append("{");
             jsonBuilder.Append("\"total\":" + totalPages + ",\"page\":" + page + ",\"records\":" + (totalRecords) + ",\"rows\"");
             jsonBuilder.Append(":[");
             for (int i = 0; i < dt.Rows.Count; i++) 
             {
                 jsonBuilder.Append("{\"i\":"+ (i) +",\"cell\":[");  
                 for (int j = 0; j < dt.Columns.Count; j++) 
                 {           
                     jsonBuilder.Append("\""); 
                     jsonBuilder.Append(dt.Rows[i][j].ToString());
                     jsonBuilder.Append("\",");
                 }
                 jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                 jsonBuilder.Append("]},");
             }
             jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
             jsonBuilder.Append("]");
             jsonBuilder.Append("}");
             return jsonBuilder.ToString();        
         }

    }
}

GetJSONFromDataTable.cs

public static string JsonForJqgrid(DataTable dt, int pageSize, int totalRecords,int page) 
{
    int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
    StringBuilder jsonBuilder = new StringBuilder();
    jsonBuilder.Append("{");
    jsonBuilder.Append("\"total\":" + totalPages + ",\"page\":" + page + ",\"records\":" + (totalRecords) + ",\"rows\"");
    jsonBuilder.Append(":[");
    for (int i = 0; i < dt.Rows.Count; i++) 
    {
        jsonBuilder.Append("{\"i\":"+ (i) +",\"cell\":[");  
        for (int j = 0; j < dt.Columns.Count; j++) 
        {           
            jsonBuilder.Append("\""); 
            jsonBuilder.Append(dt.Rows[i][j].ToString());
            jsonBuilder.Append("\",");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]},");
    }
    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
    jsonBuilder.Append("]");
    jsonBuilder.Append("}");
    return jsonBuilder.ToString();        
}

default.asp

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
         Inherits="ExampleJqGrid._Default" %>

<script type="text/javascript" src="Resources/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="Resources/js/jquery.jqGrid.js"></script>
<script type="text/javascript" src="Resources/js/ui.multiselect.js"></script>
<script type="text/javascript" src="Resources/js/jquery.layout.js"></script>
<script type="text/javascript" src="Resources/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="Resources/js/jquery-ui-1.8.2.custom.min.js"></script>
<script type="text/javascript" src="Resources/js/jqDnR.js"></script>
<script type="text/javascript" src="Resources/js/jqModal.js"></script>
<link href="Resources/themes/ui.jqgrid.css" />
<link href="Resources/themes/redmond/jquery-ui-1.8.2.custom.css" />


<script type="text/javascript">

function getProducts() 
{
    $.ajax({
        url: "/GetDataService.asmx/GetProduct",
        data:"{}",  // For empty input data use "{}",
        dataType: "json",
        type: "'GET'",
        contentType: "application/json; charset=utf-8",
        //success: successFunction
         /*complete*/success: function(jsondata) 
         {
         alert(jsondata);
            var thegrid = jQuery("#list")[0];
            thegrid.addJSONData(JSON.parse(jsondata));
         }
    });
}
function dataBindToGrid() 
{
    jQuery("#list").jqGrid({
        datatype: getProducts(), 
        colNames: ['ProductId', 'ProductName', 'Description', 'Price'],
        colModel: [{ name: 'ProductId', index: 'ProductId', width: 200, align: 'left' },
                    { name: 'ProductName', index: 'ProductName', width: 200, align: 'left' },
                    { name: 'Description', index: 'Description', width: 200, align: 'left' },
                    { name: 'Price', index: 'Price', width: 200, align: 'left' }
                   ],
        rowNum: 10,
        rowList: [5, 10, 20, 50, 100],
        pager: jQuery('#pager'),
        //imgpath: '<%= ResolveClientUrl("~/Resources/themes/redmond/images") %>',
        imgpath: '~/Resources/themes/redmond/images',
        width: 300,
        viewrecords: true
    }).navGrid(pager, { edit: true, add: false, del: false, search: false });

}
jQuery(document).ready(function() {
    $("#btnAdd").click(dataBindToGrid);  

});

</script>

        <table id="list" class="scroll">
        </table>            
        <div id="pager" class="scroll" style="text-align:center;"></div> 
        <button id="btnAdd" >Load Data</button>            
        <asp:TextBox ID="hidenfield" runat = "server" style="display:none"></asp:TextBox>
    </div>
</form>

当我提醒 jsondata 字符串时,它返回 null。

请查看并帮助我将数据加载到 jqgrid

最好的问候

【问题讨论】:

    标签: web-services json jqgrid asmx


    【解决方案1】:

    你的例子有很多问题。例如

    • 如果你在web方法上使用[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]属性,在web服务类上使用[ScriptService],那么输出参数将自动转换为JSON。 (例如,参见asmx web service, json, javascript/jquery?)。那么你就不需要实现JsonForJqgrid之类的功能了。
    • 您的程序使用了非常旧的模板。不再需要使用 datatype 作为 JSON 数据的函数。在 HTML 中使用非常旧的 jqGrid 参数 imgpathclass="scroll",因为许多版本的 jqGrid 也表明您在程序中使用了非常旧的模板,因此不再使用。
    • 小错误,例如 type: "'GET'" 而不是 type: 'GET'type: "GET"

    如果您按照datatype 作为函数的方式使用,如果您决定在应用程序中实现搜索的数据分页,则会遇到问题。

    我建议您最好查看其他示例,例如 jqgrid Page 1 of x pagerjqgrid setGridParam datatype:localjquery with ASP.NET MVC - calling ajax enabled web service。您还可以下载一个工作示例http://www.ok-soft-gmbh.com/jqGrid/WebServicesPostToJqGrid.zip,它是我作为http://www.trirand.com/blog/?page_id=393/help/pager-not-working-for-me-where-am-i-doing-wrong 答案或http://www.ok-soft-gmbh.com/jqGrid/VS2008jQueryMVC.ziphttp://www.ok-soft-gmbh.com/jqGrid/jQueryMVC.zip 的一部分创建的(请参阅另一个旧答案jquery with ASP.NET MVC - calling ajax enabled web service

    已更新:您的 JavaScript 文件的顺序也有误。 ui.multiselect.css 没有完全加载。您应该将其更改为

    不需要包含jqDnR.jsjqModal.js。如果您在jqGrid downloading 期间检查相应的模块,它应该是jquery.jqGrid.js 的一部分。 jqGrid 不需要jquery.layout.js。只有在单独使用时才应包含它。

    【讨论】:

    • @Nguyen Ngo:我在您的代码中发现了更多错误并更新了我的答案。
    猜你喜欢
    • 2012-03-27
    • 2012-03-02
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 2011-02-18
    • 1970-01-01
    相关资源
    最近更新 更多