2010-10-27 75 views
1

我創建一個Sample來測試jqgrid。將數據從Webservice(asmx)加載到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

問候

回答

3

你例子有很多的問題。例如

  • 如果使用在web服務類上的web方法[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]屬性和[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。您可以下載ASLO

修訂工作的例子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.js並且不需要jqModal.js。如果您在jqGrid downloading期間檢查相應的模塊,它應該是jquery.jqGrid.js的一部分。 jqGrid不需要jquery.layout.js。只有單獨使用時才應該包含它。

+0

@Nguyen Ngo:在代碼中發現更多錯誤並更新了我的答案。 – Oleg 2010-10-27 11:02:13