CSharper
CSharper

Reputation: 5580

Populate JqGrid inside ajax call

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.

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

Upvotes: 2

Views: 14462

Answers (2)

CSharper
CSharper

Reputation: 5580

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.

 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.

Here's the jquery code I used

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');
        }
    })      

  })
});

Upvotes: 3

Mark
Mark

Reputation: 3123

Are you actually passing a value to your controller? I see you have data: dataToSend which doesn't match to your controllers 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

Upvotes: 0

Related Questions