【问题标题】:passing data from jqGrid to webmethod将数据从 jqGrid 传递到 webmethod
【发布时间】:2011-09-11 15:50:09
【问题描述】:

这是我的 jqGrid 调用 web 方法

$(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();  
}

我的 web 方法需要 4 个参数,我试图使用 postData 传递这些参数,但由于我是新手,我不知道如何从我的 jqGrid 将数据发布到 web 方法。需要帮助被困在这个问题上大约 5 小时

你也可以帮助将页面、sidx、排序从 jqgrid 发送到 web 方法

【问题讨论】:

  • 为什么您使用 ASPX 而不是标准的 ASMX Web 服务?这是您的真正需求还是您的网站也可以欢迎 ASMX 甚至 WCF Web 服务?您使用哪个 .NET 版本和 Visual Studio?
  • 我的权限有限,而且我从未使用过 webservices 和 wcf..所以你能帮我解决 aspx 问题吗
  • 您使用哪个 .NET 版本和 Visual Studio?
  • Oleg 至少可以告诉我如何在 web 方法中传递 sidx、sord、page 和 rowNum

标签: asp.net jqgrid


【解决方案1】:

我建议您使用 ASMX 或 WCF Web 服务。在这种情况下,JSON 序列化和反序列化等许多事情都会自动为您完成。您应该只从 web 方法返回一个对象。

一般而言,WCF RESTfull 服务与 ASMX Web 服务相比具有优势,但如果您是初学者,您可以更轻松地将 ASMX Web 服务添加到您现有的项目中,以便 web.config 的所有更改都会为您制作 Visual Studio。

要将 ASMX Web 服务添加到您现有的 ASP.NET 项目中,您应该执行以下步骤。在解决方案资源管理器中选择当前项目(通常在 Visual Studio 的右侧)并键入 Ctrl+Shift+A(或单击鼠标右键并选择“添加”和“新建项目...”)您应该选择左侧的“Web”模板,然后选择“Web Service”。您可以将底部的文件名从默认的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工作项目。

【讨论】:

  • 感谢您的帮助和时间...您的回答对像我这样的菜鸟真的很有帮助
  • @bhargav:不客气!我如何理解reputation 规则你应该有投票权,但我不知道here 描述的更多限制。但这不是问题,答案现在的声誉已超过 0,因此搜索引擎会将其解释为“有帮助”。听到我的回答和演示项目对您有帮助,我很高兴。
猜你喜欢
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多