从jqGrid的数据传递给WEBMETHOD [英] passing data from jqGrid to webmethod

查看:196
本文介绍了从jqGrid的数据传递给WEBMETHOD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的jqGrid调用We​​b方法

This is my jqGrid calling web method

$(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方法,像这样的参数

as you can see im trying to pass data from here to web method with parameters like this

[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通过,但因为我是一个newbi我不知道如何从我的jqGrid发布的数据THT Web方法。需要帮忙卡住了这个周边的5小时

my web method is expecting 4 parameters which i am trying to pass using postData but since i am a newbi i dont know how to post data to tht web method from my jqGrid. Need help got stuck with this for around 5 hrs

你能还发送页面,SIDX,从排序到的jqGrid Web方法帮助

can you also help with sending the page,sidx,sort from jqgrid to web method

推荐答案

我建议您使用ASMX或WCF Web服务。在这种情况下像JSON序列化和反序列化的东西会为你自动进行。你应该只从Web方法返回一个对象。

I recommend you to use ASMX or WCF web service. In the case many things like JSON serialization and deserialization will be made automatically for you. You should just return an object from the web method.

在一般WCF REST风格服务在与ASMX Web服务的比较优势,但如果你是一个初学者,你可以更容易的添加ASMX Web服务到现有项目中,这样的web.config的所有变化都会做的Visual Studio为您服务。

In general WCF RESTfull service has advantages in comparing with ASMX web service, but if you are a beginner you can more easy add ASMX web service to your existing project so that all changes of web.config will made Visual Studio for you.

要添加ASMX Web服务到现有的ASP.NET项目,你应该做以下步骤。您可以选择在解决方案资源管理器(通常是右侧在Visual Studio),当前项目,并键入<大骨节病>控制 + <大骨节病>移 + <大骨节病> A (或点击鼠标右键,选择添加和新项...),你应该选择左侧网络模板,然后Web服务。您可以从默认的 WebService1.asmx 底部更改文件名到任何你想要的东西。例如 ProdData.asmx 。在 ProdData.asmx.cs 文件,你应该用注释 [ScriptService] 属性就行了。你还可以插入使用System.Web.Script.Services; 在文件的开头。现在你可以改变的Hello worldWeb方法的code到你所需要的。例如,以

To add ASMX web service to your existing ASP.NET project you should do following steps. You select your current project in the Solution Explorer (typically on the right side in the Visual Studio) and type Ctrl+Shift+A (or click right mouse button and choose "Add" and the "New Item…") you should choose "Web" template on the left side and then "Web Service". You can change the filename on the bottom from default WebService1.asmx to any what you want. For example ProdData.asmx. In the ProdData.asmx.cs file you should uncomment the line with [ScriptService] attribute. You can additionally insert using System.Web.Script.Services; at the beginning of the file. Now you can change the code of "Hello world" web method to what you need. For example to

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方法。 <一href=\"http://stackoverflow.com/questions/5500805/asp-net-mvc-2-0-implementation-of-searching-in-jqgrid/5501644#5501644\">The答案为您提供了范例。另外,请参阅<一个href=\"http://stackoverflow.com/questions/4029909/load-data-from-webservice-asmx-to-jqgrid-please-help-me/4031603#4031603\">this回答与code例子更多的联系。

You should of course has more complex implementation of the ProdDetails web method. The answer gives you examples. See additionally this answer for more links with code examples.

要从JavaScript调用Web方法,你应该修改你的jqGrid一点。你应该包括以下附加参数:

To call the web method from the JavaScript you should modify you jqGrid a little. You should include the following additional parameters

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 的code,我从<一大家子href=\"http://stackoverflow.com/questions/5810885/postdata-not-passing-any-parameters/5811359#5811359\">my previous答案。这是更复杂的如刚刚

The code of serializeGridData I get from my previous answer. It is more complex as just

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

在大多数情况下使用,因为你使用的功能放在 POSTDATA

used in the most cases because you use functions inside of postData.

这里你可以下载VS2010 .NET 3.5的工作项目与相应的code

Here you can download VS2010 .NET 3.5 working project with the corresponding code.

这篇关于从jqGrid的数据传递给WEBMETHOD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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