javascript 在ajax调用中填充JqGrid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18875771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:31:03  来源:igfitidea点击:

Populate JqGrid inside ajax call

javascriptajaxasp.net-mvcjqgrid

提问by CSharper

I'm trying to populate a JqGrid inside the success function of an Ajax call. My ajax call is passing a date parameter to the function which will filter the results. My grid loads, but no data is displayed and it says Loading... above my grids caption. I'm using a drop down to filter results based on date. My json data has been verified to be valid.

我正在尝试在 Ajax 调用的成功函数中填充 JqGrid。我的 ajax 调用将日期参数传递给将过滤结果的函数。我的网格已加载,但未显示任何数据,并且在我的网格标题上方显示正在加载...。我正在使用下拉菜单根据日期过滤结果。我的json数据已经验证有效。

 $(document).ready(function () {
$("[name='DDLItems']").change(function () {
    var selection = $(this).val();
    var dataToSend = {
        //holds selected value 
        idDate: selection
    };

    $.ajax({
        type: "POST",
        url: "Invoice/Filter",
        data: dataToSend,
        success: function (dataJson) {
       //      alert(JSON.stringify(dataJson));
            $("#grid").jqGrid({ //set your grid id

                data:  dataJson, //insert data from the data object we created above
                datatype: json,
                mtype: 'GET',
                contentType: "application/json; charset=utf-8",
                width: 500, //specify width; optional
                colNames: ['Invoice_Numbers', 'Amt_Totals','f', 'ff', 't'], //define column names
                colModel: [                    
                { name: 'Invoice_Number', index: 'Invoice_Number', key: true, width: 50 },
                { name: 'Amt_Total', index: 'Amt_Total', width: 50 },
                { name: 'Amt_Due', index: 'Amt_Due', width: 50 },
                { name: 'Amt_Paid', index: 'Amt_Paid', width: 50 },
                { name: 'Due_Date', index: 'Due_Date', width: 50 },

                ], //define column models

                pager: jQuery('#pager'), //set your pager div id
                sortname: 'Invoice_Number', //the column according to which data is to be sorted; optional
                viewrecords: false, //if true, displays the total number of records, etc. as: "View X to Y out of Z” optional
                sortorder: "asc", //sort order; optional
                caption: "jqGrid Example", //title of grid                    
            });
        },

-- controller

- 控制器

 [HttpPost]                     // Selected DDL value 
    public JsonResult Filter(int idDate)      
    {              
        switch (idDate)
           // switch statement goes here

        var dataJson = new UserBAL().GetInvoice(date);        

      return Json(new  { agent = dataJson}, JsonRequestBehavior.AllowGet);

回答by CSharper

Here's the answer if anyone else comes across this. This is what I ended up doing, the rows are getting filtered passed on the date parameter I'm passing to the URL of the function. Having the Grid populate inside the Ajax call also seemed like it was a problem so I had to take it out.

如果其他人遇到此问题,这就是答案。这就是我最终要做的,行被过滤传递给我传递给函数 URL 的日期参数。在 Ajax 调用中填充 Grid 似乎也是一个问题,所以我不得不将其删除。

 public JsonResult JqGrid(int idDate)
    {
         switch (idDate)

         #region switch date
            --Switch Statement--
        #endregion
        var invoices = new UserBAL().GetInvoice(date);

        return Json(invoices, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]  // pretty much does nothing, used as a middle man for ajax call 
    public JsonResult JqGridz(int idDate)
    {
        switch (idDate)
        #region switch date

          --Switch Statement--
        #endregion

        var invoices = new UserBAL().GetInvoice(date);

        return Json(invoices, JsonRequestBehavior.AllowGet);
    }

Yes these two functions seem very redundant and they are. I don't know why my post wouldn't update data, but I needed to reload the grid each time and when I did that it would call the first function. So yea the post jqGridz is kinda of just a middle man.

是的,这两个功能看起来非常多余,它们确实如此。我不知道为什么我的帖子不会更新数据,但我每次都需要重新加载网格,当我这样做时,它会调用第一个函数。所以是的 jqGridz 帖子只是一个中间人。

Here's the jquery code I used

这是我使用的 jquery 代码

var dropdown
var Url = '/Invoice/JqGrid/?idDate=0'  
         $(document).ready(function () {

$("#jqgrid").jqGrid({ 
    url: Url,
    datatype: 'json',
    mtype: 'GET', //insert data from the data object we created above 
    width: 500,  
    colNames: ['ID','Invoice #', 'Total Amount', 'Amount Due', 'Amount Paid', 'Due Date'], //define column names
    colModel: [
    { name: 'InvoiceID', index: 'Invoice_Number', key: true, hidden: true, width: 50, align: 'left' },
    { name: 'Invoice_Number', index: 'Invoice_Number', width: 50,  align: 'left'},
    { name: 'Amt_Total', index: 'Amt_Total', width: 50, align: 'left' },
    { name: 'Amt_Due', index: 'Amt_Due', width: 50, align: 'left' },
    { name: 'Amt_Paid', index: 'Amt_Paid', width: 50, align: 'left' },
    { name: 'Due_Date', index: 'Due_Date', formatter: "date", formatoptions: { "srcformat": "Y-m-d", newformat: "m/d/Y" }, width: 50, align: 'left' },

    ],                     
    pager: jQuery('#pager'), 
    sortname: 'Invoice_Number',  
    viewrecords: false, 
    editable: true,
    sortorder: "asc",  
    caption: "Invoices",       
});
$("[name='DDLItems']").change(function () {
    var selection = $(this).val();
     dropdown = {
        //holds selected value 
        idDate: selection
    };

    $.ajax({

        type: "POST",
        url: "Invoice/JqGridz",
        data: dropdown,
        async: false,
        cache: false,
        success: function (data) {         
            $("#jqgrid").setGridParam({ url: Url + selection})               
             $("#jqgrid").trigger('reloadGrid');
        }
    })      

  })
});

回答by Mark

Are you actually passing a value to your controller? I see you have data: dataToSendwhich doesn't match to your controllers idDate.

你真的在传递一个值给你的控制器吗?我看到您data: dataToSend的控制器与您的控制器不匹配idDate

Is there a reason you are trying to setup your grid this way? Do you not want to deal with paging, or I'm not even sure if your setup would handle rebuild a grid when a user picks the date for a 2nd time.

您是否有理由尝试以这种方式设置网格?您不想处理分页吗,或者我什至不确定您的设置是否会在用户第二次选择日期时处理重建网格。

My personal suggestion would be that you:

我个人的建议是:

  • setup your grid separately, hidden if you don't want it visible on page load
  • set it's datatype to local so the grid doesn't load on page load
  • on the change event:
    • show the grid
    • change the postdata parameter the grid has
    • set the url of the controller/action which will feed the data back to the grid
    • trigger a grid reload
  • 单独设置您的网格,如果您不希望它在页面加载时可见,则将其隐藏
  • 将它的数据类型设置为本地,这样网格就不会在页面加载时加载
  • 关于更改事件:
    • 显示网格
    • 更改网格具有的 postdata 参数
    • 设置将数据反馈到网格的控制器/动作的 url
    • 触发网格重新加载