views:

45

answers:

1

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. Please help me. I need this to work urgently. thanks

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>
+1  A: 

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.

Oleg
You can simply the ready function to `$(function() { /* your code */ });`, although I don't believe you actually need to use it in this case. In fact there are a lot of times you don't actually need to use the ready function.
Ryan
@Ryan: Of cause `$(function()` is the same as `jQuery(document).ready(function()`, but if somebody forget to use this I recommend always the `ready` version which shows better what it do: it wait for document DOM tree has been **fully loaded**/constructed (not a full windows with all images and videos). Because jqGrid create the grid almost only with respect of DOM manipulation it is required. I am not sure that this change along will fix the problem, but it is nevertheless really needed.
Oleg
Hey thanks for the reply. I found out where the error is already. It seems that I did not point to the correct collections. It should be pointing to "sales" rather than Model in the jsonData section.
Damien