Damien Koh
Damien Koh

Reputation: 1

jqGrid ASP.NET MVC

I am able to display my records on jqGrid however the paging is not working. I have 90 records in total and its always showing the first 10 records even though the page number did increase. I had checked the return values to jqGrid from my method and it did show a different set of records being sent to jqGrid but jqGrid is not able to display that new set of records.

Below is my code.

public JsonResult CheckReading(int page, int rows, string sidx, string sord)
{
    IList<SamplerReading> Model =
                             (IList<SamplerReading>)Session["samplerReadingArray"];
    int totalRecords = Model.Count + 1;
    int pageSize = rows;
    int pageIndex = Convert.ToInt32(page) - 1;
    int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

    string orderBy = string.Format("{0} {1}", sidx, sord);

    var sales = Model.AsQueryable()
            .OrderBy(orderBy) // Uses System.Linq.Dynamic library for sorting
            .Skip(pageIndex * pageSize)
            .Take(pageSize);

    var jsonData = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = (
              from s in Model
              select new
              {
                  i = s.ReadingId,
                  cell = new string[] {
                      s.SamplingDate.ToShortDateString(),
                      s.Ph.ToString(),
                      s.Ec.ToString(),
                      s.Arsenic.ToString(),
                      s.Temperature.ToString(), 
                      s.OilAndGrease.ToString(),
                      s.DepthToCollar.ToString()
                  }
              }).ToArray()
    };
    return Json(jsonData);
}

where

   <table id="list" cellpadding="0" cellspacing="0">
   </table>
   <div id="pager" style="text-align: center;">
   </div>

and

<script type="text/javascript">
   var gridimgpath = '/Scripts/jqgrid/themes/redmond/images';
   var gridDataUrl = '/Shared/CheckReading';
   jQuery("#list").jqGrid({
       url: gridDataUrl,
       datatype: "json",
       mtype: 'GET',
       colNames: ['Sampling Date', 'pH', 'EC', 'Arsenic', 'Temperature',
                  'Oil and Grease', 'Depth to Collar'],
       colModel: [
           { name: 'SamplingDate', index: 'SamplingDate', width: 100, align: 'left'},
           { name: 'Ph', index: 'Ph', width: 30, align: 'left' },
           { name: 'Ec', index: 'EC', width: 30, align: 'left' },
           { name: 'Arsenic', index: 'Arsenic', width: 30, align: 'left' },
           { name: 'Temperature', index: 'Temperature', width: 30, align: 'left' },
           { name: 'Oil And Grease', index: 'OilAndGrease', width: 30, align:'left'},
           { name: 'Depth To Collar', index: 'DepthToCollar', width:30,align:'right'}
       ],
       rowNum: 10,
       rowList: [10, 20, 30],
       imgpath: gridimgpath,
       height: 'auto',
       width: '900',
       pager: jQuery('#pager'),
       sortname: 'ReadingId',
       viewrecords: true,
       sortorder: "desc",
       caption: "Sampler Readings",
       edit: true
    }).navGrid("#pager", { edit: true, add: false, del: false }); 
</script>

Upvotes: 0

Views: 1123

Answers (1)

Oleg
Oleg

Reputation: 221997

You code seems to me your code has some small errors. The most important which I see is that you should place all JavaScript code inside of jQuery(document).ready(function() {/* your code */}); handle.

  1. The total or totalRecords should be equal to Model.Count and not Model.Count + 1.
  2. The usage of Convert.ToInt32(page) is not needed. You can just use page direct.
  3. You can calculate total or totalPages without usage of some float arithmetic: totalPages = (totalRecords + rows - 1) / rows. This will make the same rounding.
  4. You should returns rows having id and not i. So you should replace i = s.ReadingId to id = s.ReadingId
  5. The usage of sidx and sord directly without any checking I find dangerous. In the way you can allow SQL Injection. It is very easy to replace sord with for example

    String.Compare (sord, "desc", StringComparison.Ordinal) == 0 ? "desc": "asc"

then you can be sure that you will use no hacks inside of sord. In the same way you can verify sidx as a property of SamplerReading. It seems to me that you can use .NET Reflection: typeof(SamplerReading).GetProperties(). Instead of this you can also verify that sidx is in the list (array) of following strings 'SamplingDate','Ph','EC','Arsenic','Temperature','OilAndGrease','DepthToCollar' and use no other value of sidx.

  1. You should place all JavaScript code inside of jQuery(document).ready(function() {/* your code */}); handle.
  2. From the jqGrid definition you could remove deprecated imgpath parameter and default property align: 'left' from the every column definition. There are also no parameter edit: true in jqGrid.
  3. The HTML markup

can be reduce to

<table id="list"></table>
<div id="pager"></div>

You don't wrote which version of ASP.NET MVC you use. Probably 1.0 version. For MVC 2.0 you should use Json(jsonData, JsonRequestBehavior.AllowGet).

I recommend you verify in Fiddler of Firebug what will be send in the requests to the server and what will be send back. Moreover ids of all <tr> elements of the table must be the values of ReadingId which you send back. Verify also by setting breakpoints in the CheckReading function that the client get the response every time from the server and not from the local cache.

Upvotes: 1

Related Questions