将数据从 Webservice (asmx) 加载到 jqgrid.请帮我 [英] Load data from Webservice (asmx) to jqgrid. Please help me

查看:19
本文介绍了将数据从 Webservice (asmx) 加载到 jqgrid.请帮我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个示例来测试 jqgrid.

GetDataService.asmx:

使用系统;使用 System.Collections;使用 System.ComponentModel;使用 System.Data;使用 System.Linq;使用 System.Web;使用 System.Web.Services;使用 System.Web.Services.Protocols;使用 System.Xml.Linq;使用 System.Web.Script.Services;使用 System.Web.Script.Serialization;使用 System.Collections.Generic;使用 System.Data.SqlClient;命名空间 ExampleJqGrid{///<总结>///GetDataService 的摘要说明///</总结>[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][脚本服务][工具箱项目(假)]//要允许使用 ASP.NET AJAX 从脚本调用此 Web 服务,请取消注释以下行.//[System.Web.Script.Services.ScriptService]公共类 GetDataService : System.Web.Services.WebService{[网络方法]公共字符串 GetProduct(){SqlConnection con = new SqlConnection(@"Data Source=NGUYEN-LAPTOPSQLEXPRESS;Initial Catalog=ProductDB;Integrated Security=True");//SqlCommand cmd = new SqlCommand("SELECT * FROM Products", con);SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Products", con);数据集 ds = 新数据集();da.Fill(ds);数据表 dt = ds.Tables[0];GetJSONFromDataTable getJsonDataTable = new GetJSONFromDataTable();字符串 json = getJsonDataTable.GetJSONString(dt);字符串 jonsData = GetJSONFromDataTable.JsonForJqgrid(dt, 10, 10, 2);返回 jonsData;}}}

GetJSONFromDataTable.cs

使用系统;使用 System.Data;使用 System.Configuration;使用 System.Linq;使用 System.Web;使用 System.Web.Security;使用 System.Web.UI;使用 System.Web.UI.HtmlControls;使用 System.Web.UI.WebControls;使用 System.Web.UI.WebControls.WebParts;使用 System.Xml.Linq;使用 System.Text;使用 System.Web.Script.Serialization;命名空间 ExampleJqGrid{公共类 GetJSONFromDataTable{公共静态字符串 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 

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 

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">函数 getProducts(){$.ajax({url: "/GetDataService.asmx/GetProduct",data:"{}",//对于空输入数据使用 "{}",数据类型:json",类型:'GET'",contentType: "application/json; charset=utf-8",//成功:successFunction/*完成*/成功:函数(jsondata){警报(jsondata);var thegrid = jQuery("#list")[0];thegrid.addJSONData(JSON.parse(jsondata));}});}函数 dataBindToGrid(){jQuery("#list").jqGrid({数据类型: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' },{名称:'价格',索引:'价格',宽度:200,对齐:'左'}],行数:10,行列表:[5, 10, 20, 50, 100],寻呼机:jQuery('#pager'),//imgpath: '<%= ResolveClientUrl("~/Resources/themes/redmond/images") %>',imgpath: '~/Resources/themes/redmond/images',宽度:300,观看记录:真实}).navGrid(pager, { edit: true, add: false, del: false, search: false });}jQuery(文档).准备好(函数(){$("#btnAdd").click(dataBindToGrid);});

 
<div id="pager" class="scroll" style="text-align:center;"></div><button id="btnAdd" >加载数据</button><asp:TextBox ID="hidenfield" runat = "server" style="display:none"></asp:TextBox>

</表单>

当我提醒 jsondata string 时,它返回 null.

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

最好的问候

解决方案

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

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

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

我建议你最好看看其他一些例子,比如 jqgrid Page 1x pager, jqgrid setGridParam datatype:localjquery 与 ASP.NET MVC - 调用支持 ajax 的网络服务.您也可以下载一个工作示例 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 与 ASP.NET MVC - 调用 ajax 启用的 web 服务)

更新:您的 JavaScript 文件顺序也有误.ui.multiselect.css 没有全部加载.你应该把它改成

不需要包含 jqDnR.jsjqModal.js.如果你在 jqGrid 下载.jqGrid 不需要 jquery.layout.js.只有在单独使用时才应该包含它.

I create a Sample to test 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-LAPTOPSQLEXPRESS;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>

When i alert jsondata string , it return null.

Please review and help me to load data to jqgrid

Best regards

解决方案

You example have a lot of problems. For example

  • If you use [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute on the web method and [ScriptService] on the the web service class, then the output parameter will be automatically converted to JSON. (see asmx web service, json, javascript/jquery? for example). Then you will not need implementthe functions like JsonForJqgrid.
  • You use very old template for your program. The usage of datatype as function for JSON data is no more needed. The usage of very old jqGrid parameters imgpath and class="scroll" in HTML which no more used since many versions of jqGrid show also that you use an very old template for your program.
  • small errors like type: "'GET'" instead of type: 'GET' or type: "GET".

If you will follow the way with the usage of datatype as function you will receive problems if you decide implement data paging of searching in your application.

I recommend you better look at some other examples like jqgrid Page 1 of x pager, jqgrid setGridParam datatype:local or jquery with ASP.NET MVC - calling ajax enabled web service. You can aslo download a working example http://www.ok-soft-gmbh.com/jqGrid/WebServicesPostToJqGrid.zip which I created as a part of the http://www.trirand.com/blog/?page_id=393/help/pager-not-working-for-me-where-am-i-doing-wrong answer or http://www.ok-soft-gmbh.com/jqGrid/VS2008jQueryMVC.zip or http://www.ok-soft-gmbh.com/jqGrid/jQueryMVC.zip (see the another old answer jquery with ASP.NET MVC - calling ajax enabled web service)

UPDATED: You have also the wrong order of the JavaScript files. The ui.multiselect.css is not loaded as all. You should change it to

Including of jqDnR.js and jqModal.js is not needed. It should be a part of jquery.jqGrid.js if you check the corresponding modules during jqGrid downloading. The jquery.layout.js are not needed for jqGrid. You should include it only if you use it separately.

这篇关于将数据从 Webservice (asmx) 加载到 jqgrid.请帮我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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