我如何获得的jqGrid在后端使用ASP.NET + JSON工作? [英] How do I get jqGrid to work using ASP.NET + JSON on the backend?

查看:188
本文介绍了我如何获得的jqGrid在后端使用ASP.NET + JSON工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我回来了。我完全简化了我的问题,只是三个简单的字段,我仍然停留在使用addJSONData方法在同一行。我一直停留在这几天,不管我怎么返工Ajax调用,JSON字符串,等等等等...我无法得到这个工作!我甚至不能让它手动添加一行数据,当工作作为一个函数。任何人都可以请张贴与ASP.NET和JSON的jqGrid工作的一个工作样本?请您包括2-3字段(字符串,整数和日期preferably?)我会很高兴见到的jqGrid的工作示例,只是手动添加使用addJSONData方法的JSON对象。非常感谢!!如果我得到这个工作,我将发布所有其他张贴从ASP.NET帮助全code样品,JSON用户停留在这一点。再次。谢谢!!

tbl.addJSONData(objGridData); //错误:tbl.addJSONData不是一个函数!

下面是当我收到此消息什么是萤火虫显示:

•objGridData对象总计= 1页= 1 =记录5行= [5]

    ○页1

    记录5

    共有1

    行[对象ID = 1 = PARTNERID BCN,对象ID = 2 = PARTNERID BCN,对象ID = 3 = PARTNERID BCN,2更多... 0 =对象1 =对象2 =对象3 =对象4 =对象]

            (指数)0

                      (道具)ID(值)1
    (丙)PARTNERID(值)BCN
                  (丙)DateTimeInserted(值)星期四2008年5月29日12时08分45秒GMT-0700(太平洋夏令时)

    *有三个以上的行

下面是变量TBL(值)'Table.scroll'的值

 &LT; TABLE CELLSPACING =0的cellpadding =0BORDER =0的风格=WIDTH:245px;类=滚动grid_htable&GT;&LT; THEAD&GT;&LT; TR&GT;&LT; TH类=grid_sort grid_resize的风格=宽度:55像素;&GT;&LT; SPAN&GT; &LT; / SPAN&GT;&LT; D​​IV ID =jqgh_ID的风格=光标:指针;&GT; ID&LT; IMG src=\"http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images/sort_desc.gif\"/></DIV></TH><TH类=grid_resize的风格=宽度:90像素;&GT;&LT; SPAN&GT; &LT; / SPAN&GT;&LT; D​​IV ID =jqgh_PartnerID的风格=光标:指针;&GT; PARTNERID&LT; / DIV&GT;&LT; / TH&GT;&LT; TH类=grid_resize的风格=宽度:100像素; &GT;&LT; SPAN&GT; &LT; / SPAN&GT;&LT; D​​IV ID =jqgh_DateTimeInserted的风格=光标:指针;&GT; DateTimeInserted&LT; / DIV&GT;&LT; / TH&GT;&LT; / TR&GT;&LT; / THEAD&GT;&LT; /表&gt;

下面是完整的功能:

  $('table.scroll)。jqGrid的({
    数据类型:功能(POSTDATA){
        MTYPE:POST,
    $阿贾克斯({
        网址:'EDI.asmx / GetTestJSONString',
        键入:POST,
        的contentType:应用/ JSON的;字符集= UTF-8,
        数据:{},
        数据类型:文字,//不是JSON。让我尝试解析
        成功:函数(MSG,ST){
            如果(ST ==成功){
                 VAR的GridData;                //的带D:符号
                VAR的结果= JSON.parse(MSG);
                对(在结果VAR属性){
                    的GridData =结果[属性]
                    打破;
                }                变种objGridData =的eval((+的GridData +)); //创建具有可见数据和结构的对象
                变种TBL = jQuery的('table.scroll')[0];                警报(objGridData.rows [0] .PartnerID); //显示正确的数据                //tbl.addJSONData(objGridData); //收到的错误:addJSONData不是一个函数                //收到的错误:addJSONData不是一个函数(该使用eval如在文档中)
                //tbl.addJSONData(eval((+ objGridData +)));                //下面的一行精求,创造了一个对象,可见数据和结构
                //变种objGridData =的eval((+的GridData +));
                //但同样的事情不会在这里工作
                //tbl.addJSONData(eval((+的GridData +)));
                //萤火显示该AS的GridData的值:
               //{总:1,页:1,记录:5,行:[{ID:1,PARTNERID:BCN,DateTimeInserted 新的日期(1214412777787)},{ID:2,PARTNERID:BCN,DateTimeInserted:新的Date(1212088125000)},{ID:3,PARTNERID:BCN DateTimeInserted:新的Date(1212088125547)},{ID:4,PARTNERID:EHG,DateTimeInserted:新的Date(1235603192033)},{ID:5,PARTNERID:EMDEON ,DateTimeInserted:新的Date(1235603192000)}]}            }
        }
    });
    },
    jsonReader:{
        根:行,//哈利包含实际数据
        页:页面,//当前页面
        总:总,//在查询总页数
        记录:记录,//记录总数
        repeatitems:假的,
        ID:ID//使用PK它索引中列
    },
    colNames:
        'ID','PARTNERID','DateTimeInserted
          ]
    colModel:
    {名称:'ID',索引:'ID',宽度:55},
    {名称:'PARTNERID',索引:PARTNERID',宽度:90},
    {名称:'DateTimeInserted',索引:DateTimeInserted',宽度:100}],
    的rowNum:10,
    rowList:[10,20,30],
    imgpath:HTTP://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images',
    寻呼机:jQuery的('#寻呼机),
    sortname:'ID',
    viewrecords:真实,
    排序顺序:递减,
   标题:TEST实施例)};


解决方案

下面是一个简单的例子...

您将需要<一个href=\"https://github.com/douglascrockford/JSON-js/blob/master/json2.js\">https://github.com/douglascrockford/JSON-js/blob/master/json2.js
这个工作......

和过程的通常的jquery文件

粘贴给web服务

  //这里的下壳体属性都必须小写
//我不能找到一种方法来命名他们时,他们被序列化到JSON
//的XmlElement(yournamehere)不能用于JSON工作:(
公共类的jqGrid
{
    公共类行
    {
        公众诠释ID {搞定;组; }
        公开名单&LT;串GT;细胞{搞定;组; }        公共ROW()
        {
            电池=新的List&LT;串GT;();
        }
    }    公众诠释页{搞定;组; }
    公众诠释总{搞定;组; }
    公众诠释纪录{搞定;组; }
    公开名单&LT;行&GT;行{搞定;组; }    公众的jqGrid()
    {
        行=新的List&LT;行&GT;();
    }
}
[WebService的空间(namespace =htt​​p://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)
[ScriptService]
公共类为MyWebService:System.Web.Services.WebService
{    [的WebMethod(EnableSession =真)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)
    公众的jqGrid G​​etJQGrid(INT页,诠释的pageSize,串sortIndex,串sortDirection)
    {
        DataSet的DS = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING,udsp_GetMyData的PageIndex,pageSize的);        如果(DS == NULL || ds.Tables.Count&LT; 1)
            抛出新的异常(无法检索数据。);        jqGrid的jqGrid的=新的jqGrid();        INT I = 1;
        的foreach(DataRow的数据行的ds.Tables [0] .Rows)
        {
            JQGrid.Row行=新JQGrid.Row();            row.id = Convert.ToInt32(数据行[MyIdColumn]);            row.cell.Add(数据行[MyIdColumn]的ToString());            row.cell.Add(数据行[MyColumn]的ToString());
            projectGrid.rows.Add(行);
        }        jqGrid.page = 1; //设置此当你实际做分页......这只是一个样本
        jqGrid.records = jqGrid.rows.Count;
        jqGrid.total = jqGrid.rows.Count; //设置这在结果总页数...        返回jqGrid的;
    }
}

粘贴给你的aspx页面

 &LT;脚本类型=文/ JavaScript的&GT;
函数的getData(PDATA){
    VAR PARAMS =新的对象();
    params.page = pdata.page;
    params.pageSize = pdata.rows;
    params.sortIndex = pdata.sidx;
    params.sortDirection = pdata.sord;
    $阿贾克斯({
        键入:POST,
        的contentType:应用/ JSON的;字符集= UTF-8,
        网址:/CLM/CLM.asmx/GetProjectGrid2
        数据:JSON.stringify(PARAMS)
        数据类型:JSON
        成功:功能(数据,textStatus){
            如果(textStatus ==成功){
                变种thegrid = $(#testGrid)[0];
                thegrid.addJSONData(data.d);
            }
        },
        错误:功能(数据,textStatus){
            警报('发生错误检索数据!');
        }
    });
}VAR gridimgpath ='/ CLM / CSS / UI的亮度/图像';
$(文件)。就绪(函数(){
    $(#testGrid)。jqGrid的({
        数据类型:功能(PDATA){
            的getData(PDATA);
        },
        colNames:我的ID列,我的专栏'],
        colModel:
            {名称:'MyIdColumn',索引:MyIdColumn',宽度:150},
            {名称:'我的专栏',索引:MyColumn',宽度:250}
        ]
        的rowNum:10,
        rowList:[10,20,30],
        imgpath:gridimgpath,
        寻呼机:jQuery的('#pagerdt'),
        sortname:'ID',
        viewrecords:假的,
        排序顺序:递减,
        标题:项目,
        cellEdit:假的
    });
});
&LT; / SCRIPT&GT;

ok, I'm back. I totally simplified my problem to just three simple fields and I'm still stuck on the same line using the addJSONData method. I've been stuck on this for days and no matter how I rework the ajax call, the json string, blah blah blah...I can NOT get this to work! I can't even get it to work as a function when adding one row of data manually. Can anyone PLEASE post a working sample of jqGrid that works with ASP.NET and JSON? Would you please include 2-3 fields (string, integer and date preferably?) I would be happy to see a working sample of jqGrid and just the manual addition of a JSON object using the addJSONData method. Thanks SO MUCH!! If I ever get this working, I will post a full code sample for all the other posting for help from ASP.NET, JSON users stuck on this as well. Again. THANKS!!

tbl.addJSONData(objGridData); //err: tbl.addJSONData is not a function!!

Here is what Firebug is showing when I receive this message:

• objGridData Object total=1 page=1 records=5 rows=[5]
○ Page "1"
Records "5"
Total "1"
Rows [Object ID=1 PartnerID=BCN, Object ID=2 PartnerID=BCN, Object ID=3 PartnerID=BCN, 2 more... 0=Object 1=Object 2=Object 3=Object 4=Object]
(index) 0
(prop) ID (value) 1 (prop) PartnerID (value) "BCN" (prop) DateTimeInserted (value) Thu May 29 2008 12:08:45 GMT-0700 (Pacific Daylight Time)
* There are three more rows

Here is the value of the variable tbl (value) 'Table.scroll'

<TABLE cellspacing="0" cellpadding="0" border="0" style="width: 245px;" class="scroll grid_htable"><THEAD><TR><TH class="grid_sort grid_resize" style="width: 55px;"><SPAN> </SPAN><DIV id="jqgh_ID" style="cursor: pointer;">ID <IMG src="http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images/sort_desc.gif"/></DIV></TH><TH class="grid_resize" style="width: 90px;"><SPAN> </SPAN><DIV id="jqgh_PartnerID" style="cursor: pointer;">PartnerID </DIV></TH><TH class="grid_resize" style="width: 100px;"><SPAN> </SPAN><DIV id="jqgh_DateTimeInserted" style="cursor: pointer;">DateTimeInserted </DIV></TH></TR></THEAD></TABLE>

Here is the complete function:

 $('table.scroll').jqGrid({  
    datatype: function(postdata) {    
        mtype: "POST",    
    $.ajax({  
        url: 'EDI.asmx/GetTestJSONString',  
        type: "POST",  
        contentType: "application/json; charset=utf-8",  
        data: "{}",  
        dataType: "text", //not json . let me try to parse  
        success: function(msg, st) {  
            if (st == "success") {                    
                 var gridData;  

                //strip of "d:" notation  
                var result = JSON.parse(msg);   
                for (var property in result) {  
                    gridData = result[property];  
                    break;  
                }  

                var objGridData = eval("(" + gridData + ")"); //creates an object with visible data and structure  
                var tbl = jQuery('table.scroll')[0];  

                alert(objGridData.rows[0].PartnerID); //displays the correct data  

                //tbl.addJSONData(objGridData); //error received: addJSONData not a function  

                //error received: addJSONData not a function (This uses eval as shown in the documentation)  
                //tbl.addJSONData(eval("(" + objGridData + ")"));   

                //the line below evaluates fine, creating an object and visible data and structure  
                //var objGridData = eval("(" + gridData + ")");  
                //BUT, the same thing will not work here  
                //tbl.addJSONData(eval("(" + gridData + ")"));  
                //FIREBUG SHOWS THIS AS THE VALUE OF gridData:  
               // "{"total":"1","page":"1","records":"5","rows":[{"ID":1,"PartnerID":"BCN","DateTimeInserted":new Date(1214412777787)},{"ID":2,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125000)},{"ID":3,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125547)},{"ID":4,"PartnerID":"EHG","DateTimeInserted":new Date(1235603192033)},{"ID":5,"PartnerID":"EMDEON","DateTimeInserted":new Date(1235603192000)}]}"         

            }  
        }  
    });  
    },  
    jsonReader: {  
        root: "rows", //arry containing actual data  
        page: "page", //current page  
        total: "total", //total pages for the query  
        records: "records", //total number of records  
        repeatitems: false,  
        id: "ID" //index of the column with the PK in it   
    },  
    colNames: [  
        'ID', 'PartnerID', 'DateTimeInserted'  
          ],    
    colModel: [    
    { name: 'ID', index: 'ID', width: 55 },    
    { name: 'PartnerID', index: 'PartnerID', width: 90 },  
    { name: 'DateTimeInserted', index: 'DateTimeInserted', width: 100}],  
    rowNum: 10,  
    rowList: [10, 20, 30],  
    imgpath: 'http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images',  
    pager: jQuery('#pager'),  
    sortname: 'ID',  
    viewrecords: true,  
    sortorder: "desc",  
   caption: "TEST Example")};

解决方案

Here is a simple example...

You will need https://github.com/douglascrockford/JSON-js/blob/master/json2.js for this to work...

and of course the usual jquery files.

Paste this to a webservice

// The lower case properties here are required to be lower case
// I cant find a way to rename them when they are serialized to JSON
// XmlElement("yournamehere") does not work for JSON :(
public class JQGrid
{
    public class Row
    {
        public int id { get; set; }
        public List<string> cell { get; set; }

        public Row()
        {
            cell = new List<string>();
        }
    }

    public int page { get; set; }
    public int total { get; set; }
    public int records { get; set; }
    public List<Row> rows { get; set; }

    public JQGrid()
    {
        rows = new List<Row>();
    }
}


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyWebService : System.Web.Services.WebService
{

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
    public JQGrid GetJQGrid(int page, int pageSize, string sortIndex, string sortDirection)
    {
        DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, "udsp_GetMyData",pageIndex, pageSize);

        if (ds == null || ds.Tables.Count < 1)
            throw new Exception("Unable to retrieve data.");

        JQGrid jqGrid = new JQGrid();

        int i = 1;
        foreach (DataRow dataRow in ds.Tables[0].Rows)
        {
            JQGrid.Row row = new JQGrid.Row();

            row.id = Convert.ToInt32(dataRow["MyIdColumn"]);

            row.cell.Add(dataRow["MyIdColumn"].ToString());

            row.cell.Add(dataRow["MyColumn"].ToString());


            projectGrid.rows.Add(row);
        }

        jqGrid.page = 1; // Set this when you are actually doing paging... this is just a sample
        jqGrid.records = jqGrid.rows.Count;
        jqGrid.total = jqGrid.rows.Count;  // Set this to total pages in your result...

        return jqGrid;
    }
}

Paste this to your aspx page

<script type="text/javascript">
function getData(pdata) {
    var params = new Object();
    params.page = pdata.page;
    params.pageSize = pdata.rows;
    params.sortIndex = pdata.sidx;
    params.sortDirection = pdata.sord;


    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/CLM/CLM.asmx/GetProjectGrid2",
        data: JSON.stringify(params),
        dataType: "json",
        success: function(data, textStatus) {
            if (textStatus == "success") {
                var thegrid = $("#testGrid")[0];
                thegrid.addJSONData(data.d);
            }
        },
        error: function(data, textStatus) {
            alert('An error has occured retrieving data!');
        }
    });
}

var gridimgpath = '/clm/css/ui-lightness/images';
$(document).ready(function() {
    $("#testGrid").jqGrid({
        datatype: function(pdata) {
            getData(pdata);
        },
        colNames: ['My Id Column', 'My Column'],
        colModel: [
            { name: 'MyIdColumn', index: 'MyIdColumn', width: 150 },
            { name: 'My Column', index: 'MyColumn', width: 250 }
        ],
        rowNum: 10,
        rowList: [10, 20, 30],
        imgpath: gridimgpath,
        pager: jQuery('#pagerdt'),
        sortname: 'id',
        viewrecords: false,
        sortorder: "desc",
        caption: "Projects",
        cellEdit: false
    });
});
</script>

这篇关于我如何获得的jqGrid在后端使用ASP.NET + JSON工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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