2011-06-09 92 views
3

這是我的jqGrid調用Web方法從jqGrid的數據傳遞到WEBMETHOD

$(document).ready(function() { 
    jQuery("#prodgrid").jqGrid({ 
     url: 'product_brow.aspx/ProdGrid', 
     postData: { 
      ddlproductstatus: function() { 
       return $("#<%=ddlProductStatus.ClientID%>").val(); 
      }, 
      ddlproducttype: function() { 
       return $("#<%=ddlProductType.ClientID%>").val(); 
      }, 
      txtkeywordsearch: function() { 
       return $("#<%=txtKeywordSearch.ClientID%>").val(); 
      }, 
      hdnMerchantId: function() { 
       return $("#<%=hdnmerchantId.ClientID%>").val(); 
      } 
     }, 
     mtype: 'POST', 
     serializeEditData: function (postData) { 
      return JSON.stringify(postData); 
     } , 
     colNames: ['Code', 'Title', 'Price', 'Product Group', 'Edit', 'Status'], 
     colModel: [ 
      { name: 'Code', index: 'Code', width: 15, align: 'center' }, 
      { name: 'Title', index: 'Title', width: 40, align: 'center' }, 
      { name: 'Price', index: 'Price', width: 55 }, 
      { name: 'Product Group', index: 'Product Group', width: 55 }, 
      { name: 'Edit', index: 'Edit', width: 40 }, 
      { name: 'Status', index: 'Status', width: 40}], 
     pager: '#prod_pager', 
     rowList: [10, 20, 30], 
     sortname: 'Code', 
     sortorder: 'desc', 
     rowNum: 10, 
     loadtext: "Loading....", 
     shrinkToFit: true, 
     multiselect: true, 
     emptyrecords: "No records to view", 
     width: x - 40, 
     height: 230, 
     rownumbers: true, 
     subGrid: true, 
     caption: 'Products' 
     // editurl: 'Departments.aspx' 
    }); 
    jQuery("#prodgrid").jqGrid('navGrid', '#prod_pager', 
     { edit: false, add: false, del: true, excel: true, search: false }); 
}); 

,你可以看到我嘗試從這裏帶參數的數據傳遞到Web方法這樣

[WebMethod] 
public static string ProdDetails(string ddlproductstatus, 
           string ddlproducttype, 
           string txtkeywordsearch, 
           string hdnMerchantId) 
{ 
    StringBuilder sbReturnJson = new StringBuilder(); 
    string strReturnJson = string.Empty; 
    StringBuilder sbCell = new StringBuilder(); 

    try 
    { 
     string sort = HttpContext.Current.Request.Form["sidx"].ToString(); 
     string strSortDerection = HttpContext.Current.Request.Form["sord"].ToString(); 
     int iPage = Convert.ToInt32(HttpContext.Current.Request.Form["page"]);//get the requested page 
     string strLimit = HttpContext.Current.Request.Form["rows"].ToString(); // get how many rows we want to have into the grid 
     string strStart = Convert.ToString(int.Parse(strLimit) * (iPage - 1)); 
     string strEnd = Convert.ToString(int.Parse(strStart) + int.Parse(strLimit)); 

     string pageNo = string.Empty; 
     ProductDal oProductDal = new ProductDal(); 

     // bind data to gridview 

     System.Data.DataTable oDataTable; 

     if (txtkeywordsearch.Trim().Length == 0) 
     { 
      oDataTable = oProductDal.GetAllProductDtToDisplayTest(Convert.ToInt32(hdnMerchantId), ddlproducttype, 
       ddlproductstatus, iPage, Convert.ToInt32(strLimit)); 
     } 
     else 
     { 
      oDataTable = oProductDal.GetAllProductDtToDisplayBySearchStringTest(Convert.ToInt32(hdnMerchantId), ddlproducttype, 
       ddlproductstatus, txtkeywordsearch.Trim(), iPage, Convert.ToInt32(strLimit)); 
     } 

     // keep values in session to use in product detail page to retrieve records. 
     //Session["ProductType"] = ddlproducttype; 
     // Session["ProductStatus"] = ddlproductstatus; 

     if (txtkeywordsearch.Trim().Length != 0) 
     { 
      // Session["SearchKeyword"] = txtkeywordsearch; 
     } 


     // hlnkExportToExcel.Visible = false; 

     // calculate the total number of records. 
     int totalRows = 0; 

     if (txtkeywordsearch.Trim().Length == 0) 
     { 
      totalRows = oProductDal.CountAllProductDtToDisplay(Convert.ToInt32(hdnMerchantId), ddlproducttype, 
        ddlproductstatus); 
     } 

     else 
     { 
      totalRows = oProductDal.CountAllProductDtToDisplayBySearchString(Convert.ToInt32(hdnMerchantId), ddlproducttype, 
        ddlproductstatus, txtkeywordsearch.Trim()); 
     } 

     //if (!IsPostBack) 
     //{ 
     // gvProductBrow.PageIndex = _currentPageNumber; 
     //} 


     var count = oDataTable.Rows.Count; 

     sbReturnJson.Append("{\"page\":\"" + iPage + "\",\"records\":\"" + count + "\",\"rows\":["); 
     foreach (DataRow row in oDataTable.Rows) 
     { 
      // int depid = Convert.ToInt32(row[1].ToString()); 
      // var Editbutton = "<img Class='GridEdit' onclick='showjQueryDialog(" + depid + ");' src='Images/edit.jpeg'></img>"; 
      //<a href='#' Class='GridEdit' onclick='showjQueryDialog(" + depid + ");'>Edit</a> 
      string code = (row[1].ToString()); 
      string title = (row[4].ToString()); 
      string price = (row[7].ToString()); 
      string product_group = (row[5].ToString()); 
      string edit = (row[0].ToString()); 
      string status = (row[2].ToString()); 

      sbCell.Append("{\"cell\":[\"" + code + "\",\"" + title + "\",\"" + price + "\",\"" + product_group + "\",\"" + edit + "\",\"" + status + "\"]}"); 
      sbCell.Append(","); 
     } 

     // lblNoOfRows.Text = totalRows + " record(s) found"; 

     sbReturnJson.Append(sbCell.ToString().TrimEnd(',')); 
     double dCount = Math.Ceiling(Convert.ToDouble(count/int.Parse(strLimit))); 
     int iCount = int.Parse(dCount.ToString()) + 1; 
     sbReturnJson.Append("],\"total\":\"" + iCount + "\"}"); 

     //lblTopPageNo.Text = (gvProductBrow.PageIndex + 1) + "/" + CalculateTotalPages(totalRows); 
     //lblBottomPageNo.Text = (gvProductBrow.PageIndex + 1) + "/" + CalculateTotalPages(totalRows); 
     //ViewState["NoOfPages"] = CalculateTotalPages(totalRows); 

    } 
    catch (Exception ex) 
    { 
     ExceptionLogger.LogException(ex); 
     //lblErrorMessage.Text += Resources.Resource.Product_errMsgLoadProduct; 
     return "Error"; 
    } 
    return sbReturnJson.ToString(); 
} 

我的網站方法期待4個參數,我試圖通過使用postData但由於我是一個newbi我不知道如何發佈數據到我的jqGrid網絡方法。需要幫助被困這個周邊的5小時

可你也發送頁面,SIDX幫助,從排序的jqGrid到Web方法

+0

爲什麼使用ASPX而不是標準的ASMX網絡服務?它是你真正的需求還是ASMX,甚至WCF Web服務也可以在你的網站上受歡迎?你使用哪個.NET版本和Visual Studio? – Oleg 2011-06-09 12:26:34

+0

我有限的權限,我從來沒有使用過的web服務和wcf ..所以你可以請幫助aspx – bhargav 2011-06-09 12:28:14

+0

你使用哪個.NET版本和Visual Studio? – Oleg 2011-06-09 12:34:47

回答

5

我建議你使用ASMX或WCF的Web服務。在這種情況下,很多事情都會自動爲您自動生成JSON序列化和反序列化。您應該只從web方法返回一個對象。

一般來說,WCF RESTfull服務與ASMX Web服務相比具有優勢,但如果您是初學者,則可以更輕鬆地將ASMX Web服務添加到現有項目中,以便web.config的所有更改都將爲您創建Visual Studio 。

要將ASMX web服務添加到您現有的ASP.NET項目中,您應該執行以下步驟。您可以選擇在Solution Explorer(通常在右側在Visual Studio)當前項目,並鍵入按Ctrl + + 一個(或單擊鼠標右鍵,選擇「添加」和「新項... 「)你應該選擇左側的」Web「模板,然後選擇」Web服務「。您可以將底部的文件名從默認WebService1.asmx更改爲您想要的任何內容。例如ProdData.asmx。在ProdData.asmx.cs文件中,您應取消註釋[ScriptService]屬性的行。您還可以在文件的開頭插入using System.Web.Script.Services;。現在,您可以將「Hello world」網頁方法的代碼更改爲您所需的內容。例如,要

using System.Collections.Generic; 
using System.Web.Services; 
using System.Web.Script.Services; 

namespace TestWebApplicationWithjqGrid 
{ 
    public class GridRow { 
     public string id { get; set; } 
     public List<string> cell { get; set; } 
    } 
    public class GridData { 
     public int page { get; set; } 
     public int total { get; set; } 
     public int records { get; set; } 
     public List<GridRow> rows { get; set; } 
    } 
    [WebService (Namespace = "http://tempuri.org/")] 
    [WebServiceBinding (ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem (false)] 
    [ScriptService] 
    public class ProdData: WebService 
    { 
     [WebMethod] 
     public GridData ProdDetails(string sidx, string sord, int page, int rows, 
            string ddlproductstatus, string ddlproducttype, string txtkeywordsearch, int hdnMerchantId) { 
      return new GridData {page = 1, total = 1, records = 2, rows = new List<GridRow> { 
       new GridRow {id = "i1", cell = new List<string> {"Code1", "Title1", "Price1", "Group1", "Edit1", "Status1"}}, 
       new GridRow {id = "i2", cell = new List<string> {"Code2", "Title2", "Price2", "Group2", "Edit2", "Status2"}} 
      }}; 
     } 
    } 
} 

你當然應該有更復雜的實施ProdDetails Web方法。 The answer給你的例子。有關代碼示例的更多鏈接,另請參閱this answer

要從JavaScript調用Web方法,您應該修改一下jqGrid。您應該包括以下附加參數

datatype: 'json', 
ajaxGridOptions: { contentType: "application/json"}, 
serializeGridData: function (postData) { 
    var propertyName, propertyValue, dataToSend = {}; 
    for (propertyName in postData) { 
     if (postData.hasOwnProperty(propertyName)) { 
      propertyValue = postData[propertyName]; 
      if ($.isFunction(propertyValue)) { 
       dataToSend[propertyName] = propertyValue(); 
      } else { 
       dataToSend[propertyName] = propertyValue 
      } 
     } 
    } 
    return JSON.stringify(dataToSend); 
}, 
jsonReader: { 
    root: "d.rows", 
    page: "d.page", 
    total: "d.total", 
    records: "d.records" 
} 

serializeGridData的代碼,我從my previous answer得到。這是因爲剛剛

serializeGridData: function (postData) { return JSON.stringify(postData); } 

在大多數情況下使用,因爲您使用的postData內部功能更加複雜。

Here您可以使用相應的代碼下載VS2010 .NET 3.5工作項目。

+0

thanx爲您的幫助和時間...您的答案是真的有用像我這樣的noob – bhargav 2011-06-10 06:03:36

+0

我無法添加任何upvote becoz我的低聲譽 – bhargav 2011-06-10 06:22:08

+0

@bhargav:不客氣!我如何理解[聲譽](http://stackoverflow.com/faq#reputation)規則,您應該擁有投票權,但我不知道更多限制,如[此處]所述(http://meta.stackexchange。 COM /問題/ 5212 /是 - 有 - 任何投票權,限制/ 5213#5213)。但這不是問題,現在的答案現在有更多的聲譽,所以搜索引擎會將其解釋爲「有用」。我聽說我的回答和演示項目對你有幫助。 – Oleg 2011-06-10 07:52:18