JQgrid Sorting MVC3 - asp.net-mvc-3

In my CS page i have following code
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
Employee _emp = new Employee();
List<Employee> _lstemp = _emp.GetallEmp();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = _lstemp.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from emp in _lstemp
select new
{
i = emp.ID,
cell = new string[] { emp.ID.ToString(), emp.FirstName.ToString(), emp.LastName.ToString(),emp.Age.ToString(),emp.State.ToString(),emp.Country.ToString() }
}).ToArray()
};
return Json(jsonData);
}
My Model Is
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string State { get; set; }
public string Country { get; set; }
public List<Employee> GetallEmp()
{
List<Employee> list = new List<Employee>()
{
new Employee{ID=1,FirstName="Asish",LastName="Nehra",Age=25,State="A",Country="India"},
new Employee{ID=2,FirstName="Nsish",LastName="Oehra",Age=35,State="B",Country="Sri Lanka"},
new Employee{ID=3,FirstName="Psish",LastName="Lehra",Age=26,State="C",Country="Bangladesh"},
new Employee{ID=4,FirstName="Jsish",LastName="Hehra",Age=25,State="D",Country="Australia"},
new Employee{ID=5,FirstName="Usish",LastName="Tehra",Age=85,State="E",Country="Kenya"},
new Employee{ID=6,FirstName="Rsish",LastName="Lehra",Age=15,State="F",Country="India"},
new Employee{ID=7,FirstName="Isish",LastName="Eehra",Age=5,State="G",Country="Pakistan"},
new Employee{ID=8,FirstName="Asish",LastName="Nehra",Age=25,State="A",Country="India"},
new Employee{ID=9,FirstName="Nsish",LastName="Oehra",Age=35,State="B",Country="Sri Lanka"},
new Employee{ID=10,FirstName="Psish",LastName="Lehra",Age=26,State="C",Country="Bangladesh"},
new Employee{ID=11,FirstName="Jsish",LastName="Hehra",Age=25,State="D",Country="Australia"},
new Employee{ID=12,FirstName="Usish",LastName="Tehra",Age=85,State="E",Country="Kenya"},
new Employee{ID=13,FirstName="Rsish",LastName="Lehra",Age=15,State="F",Country="India"},
new Employee{ID=14,FirstName="Isish",LastName="Eehra",Age=5,State="G",Country="Pakistan"},
new Employee{ID=15,FirstName="Asish",LastName="Nehra",Age=25,State="A",Country="India"},
new Employee{ID=16,FirstName="Nsish",LastName="Oehra",Age=35,State="B",Country="Sri Lanka"},
new Employee{ID=17,FirstName="Psish",LastName="Lehra",Age=26,State="C",Country="Bangladesh"},
new Employee{ID=18,FirstName="Jsish",LastName="Hehra",Age=25,State="D",Country="Australia"},
new Employee{ID=19,FirstName="Usish",LastName="Tehra",Age=85,State="E",Country="Kenya"},
new Employee{ID=20,FirstName="Rsish",LastName="Lehra",Age=15,State="F",Country="India"},
new Employee{ID=21,FirstName="Isish",LastName="Eehra",Age=5,State="G",Country="Pakistan"},
};
return list;
}
}
In my Cshtml page
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData/',
datatype: 'json',
mtype: 'POST',
colNames: ['ID', 'FirstName', 'LastName', 'Age', 'State', 'Country'],
colModel: [
{ name: 'ID', index: 'ID', width: 40, align: 'left' },
{ name: 'FirstName', index: 'FirstName', width: 80, align: 'left' },
{ name: 'LastName', index: 'LastName', width: 80, align: 'left' },
{ name: 'Age', index: 'Age', width: 80, align: 'left' },
{ name: 'State', index: 'State', width: 80, align: 'left' },
{ name: 'Country', index: 'Country', width: 80, align: 'left' }],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'ID, FirstName, LastName, Age, State, Country',
sortorder: "Asc",
viewrecords: true,
imgpath: '/content/images',
autowidth: true,
width: '100%',
height: '100%',
multiselect: false,
caption: "Grid example",
loadComplete: function() {
//jQuery("#myGridID").trigger("reloadGrid"); // Call to fix client-side sorting
}
});
//jQuery("#list").jqGrid('navGrid', '#pager', { add: true, edit: true, del: true });
jQuery("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false }, {}, {}, {}, { multipleSearch: true, multipleGroup: true, showQuery: true });
});
</script>
How can i sort all the columns..I just want to sort all my fields by making sortable:true for all fields
EDIT The <script> was not correct formatted

In your controller you will need to use an OrderBy and then use the sidx, sord values passed to your controller by your grid. I'm also including paging in the example below so your grid can only display a page of rows from your data set.
List pagedQuery = _lstemp.AsQueryable().OrderBy(sidx + " " + sord).Skip((page - 1) * rows).Take(rows);
In your colModel (jqGrid setup) you would set each column you want to be sortable with a property par of
sortable: false, or sortable: true
If you want everything to be sortable you could use
$.extend($.jgrid.defaults, {sortable: true});
You will be able to examine your POST to see the jqGrid telling the controller which column to sort by as well as the direction .
Note: You will need the System.Linq.Dynamic dll for this particular OrderBy syntax. This dll is available:
As a nuget package
On the project page

Related

How to set Total Pages in JQGrid if I'm using server side paging?

I'm new to JQGrid and learning the paging currently. I'm trying to implement server side paging.
Consider I have 45 records. Since, Server side returns the requested records of a specified page based on page size(say 10), my pager changes to 1 immediately after clicking next button. I'm not able to move on to further pages since the total page is 1 now. Total page is automatically getting calculated based on the records present. So how to manage the total pages value in this case?
$("#jqGridOutbox").jqGrid({
datatype: 'json',
mtype: 'POST',
colNames: ['Title', 'Submitted By', 'Assigned To', 'Submitted On', 'History', 'WorkFlow Name'],
colModel: [
{ name: 'TitleOut', index: 'Title', width: 173, sortable: true, search: true, formatter: ShowItemFormatterOutbox },
{ name: 'CreatedByOut', index: 'CreatedBy', width: 173, sortable: true, searchoptions: {} },
{ name: 'PendingOnOut', index: 'PendingOn', width: 173, sortable: true, searchoptions: {} },
{ name: 'CreatedOnOut', index: 'CreatedOn', width: 173, sortable: true, searchoptions: {} },
{ name: 'HistoryOut', index: 'History', width: 80, sortable: false, search: false, formatter: ViewHistoryFormatter },
{ name: 'WorkFlowNameOut', index: 'WorkFlowName', width: 170, sortable: true, search: true }
],
datatype: function (postData) { getDataOutBox(postData, OutMode, OutPageNumber); },
ajaxGridOptions: { contentType: "application/json" },
loadonce: 'false',
viewrecords: 'true',
width: 987,
viewsortcols: [true, 'vertical', true],
height: 250,
rowList: [2, 5, 10, 20, 30, 100],
hidegrid: 'false',
rowNum: 2,
autowidth: true,
gridview: true,
shrinkToFit: false,
showQuery: 'true',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id: "Title",
userdata: "userdata",
repeatitems: true
},
gridComplete: function () {
$("#load_jqGridOutbox").hide();
$("tr.jqgrow:odd").css("background", "white");
$("tr.jqgrow:even").css("background", "#f7f7f7");
},
pager: '#jqGridOutboxPager',
pagerpos: 'center'
});
The function mapped to datatype is GetDataOutBox()
function getDataOutBox(pdata, mode, pageNumber) {
var params = new Object();
params.page = pdata.page;
params.pageSize = pdata.rows;
params.sortIndex = pdata.sidx;
params.sortDirection = pdata.sord;
params.Title = $("#gs_TitleOut").val() == undefined ? '' : $("#gs_TitleOut").val();
params.CreatedBy = $("#gs_CreatedByOut").val() == undefined ? '' : $("#gs_CreatedByOut").val();
params.PendingOn = $("#gs_PendingOnOut").val() == undefined ? '' : $("#gs_PendingOnOut").val();
params.CreatedOn = $("#gs_CreatedOnOut").val() == undefined ? '' : $("#gs_CreatedOnOut").val();
params.WorkFlowName = $("#gs_WorkFlowNameOut").val() == undefined ? '' : $("#gs_WorkFlowNameOut").val();
params.mode = mode;
params.pageNumber = pageNumber;
$("#load_jqGridOutbox").show();
$.ajax({
url: 'ClaySysWorkFlowDashBoard.aspx/GetOutboxData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#jqGridOutbox")[0];
grid.addJSONData(data.d);
//$("#jqGridOutbox")[0].updatepager(false, true);
}
},
error: function () {
alert("An error has occured retrieving the data!");
}
});
}
The model which gets returned is
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>();
}
}
Based on the page number, I select only the respective set of 10 records. Thus after returning that, the total pages changes to 1.

Export To Excel JQGrid Data in Spring/JSP

I'm developing a Web application using Spring 3.0, JSP, Tiles.
On one of the JSP pages I've to display some data using JQgrid and I've to provide a button to facilitate the user to export the data in JQgrid to an Excel Sheet.
I've successfully created the JQgrid and am able to display the data.
I was wondering how to implement the "Export To Excel" functionality on the click of a button.
I tried looking for several solutions but couldn't find anything concrete.
My handler code:
#RequestMapping(method = RequestMethod.POST, value = "/workQueue")
#ResponseBody
public JqgridResponse loadXXXXXX(#RequestParam int page, #RequestParam int rows, #RequestParam String sidx, #RequestParam String sord){
List<ReferralCase> referrals = XXXXService.getReferralCases();
int endLimit = page * rows;
int startLimit = endLimit - rows;
if (endLimit > referrals.size()) {
endLimit = referrals.size();
}
JqgridResponse response = new JqgridResponse();
response.setRows(referrals.subList(startLimit, endLimit));
response.setPage(page);
response.setRecords(referrals.size());
response.setTotal((referrals.size() / rows) + 1);
return response;
}
My JSP/JS Code:
$("#XXXXWorkQueueGrid").jqGrid({
url:contextRoot+'/dart/workQueue',
datatype: 'json',
mtype: 'POST',
colNames: ['ID','Created','Last Name','First Name','A1','A2','Status','Updated','Workflow'],
colModel: [
{ name: 'recordId', index: 'recordId', width: 30 },
{ name: 'creationDate', index: 'creationDate', width: 40 },
{ name: 'lastName', index: 'lastName', width: 60 },
{ name: 'firstName', index: 'firstName', width: 60 },
{ name: 'A1', index: 'A1', width: 25 },
{ name: 'A2', index: 'A2', width: 25 },
{ name: 'status', index: 'status', width: 40 },
{ name: 'updateDate', index: 'updateDate', width: 40 },
{ name: 'workflow', index: 'workflow', width: 90 }
],onPaging: function() {
$(this).setGridParam({datatype: 'json'}).triggerHandler("reloadGrid");
},loadComplete: function() {
$(this).setGridParam({datatype: 'json'}).triggerHandler("reloadGrid");
},loadError: function(xhr,st,err) {
alert(err);
},onSelectRow : function(rowid, status, e) {
var selRow = $(this).getGridParam("selrow");
var selRecordId = $(this).getCell(selRow, 'recordId');
window.location = (contextRoot+"XXXX/referralDetails?recId=" + selRecordId );
},
pager: '#XXXXWorkQueuePager',
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "total",
records: "records"
},
sortorder: "asc",
sortname: 'recordId',
gridview: true,
viewrecords: true,
hoverrows : false,
autowidth: true,
height: 'auto',
rowNum: 12,
forceFit: true,
altRows:true
});
$("#XXXXXWorkQueueGrid").jqGrid('navGrid','#XXXXXWorkQueuePager',{edit:false, add:false, del:false, search:false});
});
JqgridResponse is just a custom DAO class created by me.
Any help is appreciated!
You can generate a new Excel file using Apache POI and use Spring AbstractExcelView to make it downloadable. Just follow this turorial to setup everything.

jqgrid retrieving empty rows using webapi (REST)

I'm using jqgrid in an ASPNET MVC4 project with WebApi (REST), Entity Framework 5 using Unit Of Work and Repository patterns.
My problem is that I see the data flowing as json to the browser and I see three rows in the grid, but those rows are empty, and the data is not shown (three empty rows in the grid).
This is method to get the data in the WebApi controller:
public dynamic GetGridData(int rows, int page, string sidx, string sord)
{
var pageSize = rows;
var index = sidx;
var order = sord;
var categories = Uow.Categories.GetAll().OrderBy(t => (string.IsNullOrEmpty(index) ? "Id" : index) + " " + (order ?? "desc"));
var pageIndex = Convert.ToInt32(page) - 1;
var totalRecords = categories.Count();
var totalPages = (int)Math.Ceiling((float) totalRecords / (float) pageSize);
var categoriesPage = categories.Skip(pageIndex * pageSize).Take(pageSize).ToList();
return new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from category in categoriesPage
select new
{
id = category.Id.ToString(),
cell = new string[]
{
category.Id.ToString(),
category.Name,
category.Description
}
}).ToArray()
};
}
This is the json received in the browser
{
"total": 1,
"page": 1,
"records": 3,
"rows": [{
"id": "1",
"cell": ["1", "Category 1", null]
}, {
"id": "3",
"cell": ["3", "Category 3", "asAS"]
}, {
"id": "4",
"cell": ["4", "Category 4", null]
}]
}
This is the .js file with jqgrid
jQuery("#ajaxGrid").jqGrid({
url: $("#ServiceUrl").val(),
datatype: "json",
jsonReader: { repeatitems: false, id: "Id" },
colNames: ['Id', 'Name', 'Description'],
colModel: [
{ name: 'id', editable: true, sortable: true, hidden: true, align: 'left' },
{ name: 'name', editable: true, sortable: true, hidden: false, align: 'left' },
{ name: 'description', editable: true, sortable: true, hidden: false, align: 'left' }
],
mtype: 'GET',
rowNum: 15,
pager: '#ajaxGridPager',
rowList: [10, 20, 50, 100],
caption: 'List of Categories',
imgpath: $("#ServiceImagesUrl").val(),
altRows: true,
shrinkToFit: true,
viewrecords: true,
autowidth: true,
height: 'auto',
error: function(x, e)
{
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
function updateDialog(action) {
return {
url: $("#ServiceUrl").val(),
closeAfterAdd: true,
closeAfterEdit: true,
afterShowForm: function (formId) { },
modal: true,
onclickSubmit: function (params) {
var list = $("#ajaxGrid");
var selectedRow = list.getGridParam("selrow");
params.url += "/" + list.getRowData(selectedRow).Id;
params.mtype = action;
},
width: "300",
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (data) {
delete data.oper;
return JSON.stringify(data);
}
};
}
jQuery("#ajaxGrid").jqGrid(
'navGrid',
'#ajaxGridPager',
{
add: true,
edit: true,
del: true,
search: false,
refresh: false
},
updateDialog('PUT'),
updateDialog('POST'),
updateDialog('DELETE')
);
BTW, If I want to return jqGridData instead the dynamic, How should I do it? Did is showing empty rows as well:
public class jqGridData<T> where T : class
{
public int page { get; set; }
public int records { get; set; }
public IEnumerable<T> rows { get; set; }
public decimal total { get; set; }
}
public jqGridData<Category> GetGridData(int rows, int page, string sidx, string sord)
{
var pageSize = rows;
var index = sidx;
var order = sord;
var categories = Uow.Categories.GetAll().OrderBy(t => (string.IsNullOrEmpty(index) ? "Id" : index) + " " + (order ?? "desc"));
var pageIndex = Convert.ToInt32(page) - 1;
var totalRecords = categories.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var categoriesPage = categories.Skip(pageIndex * pageSize).Take(pageSize);
return new jqGridData<Category>
{
page = page,
records = totalRecords,
total = totalPages,
rows = categoriesPage
};
}
Thanks in advance!!! Guillermo.
Ok, I can't believe it, but it was the case in the name of the columns. First letter should be capitalized as it's capitalized in the data sent.

JQgrid Web Api Json on a SPA

I just found JQGrid , and think that JQgrid is very mature and perfect to use with Web API
I have a few questions:
we are using Web Api and have the following HTML code and Controller.
The Image field loses its data when It comes back to the controller. Google debugger shows data for the image field on the HTML, but if I set a breakpoint on the Put method inside the controller, Visual Studio , I can see the product entity with all its fields filled with data, all but one; the image field is null.
It took me some digging to get this working , therefore I decided to share the HTML code + the WebApi controller it with the community.
1- am I am doing this right (Grid parameters) ?
2-Why the image fields comes back null ?
3-How can I implement a search ?
this will not get called
public dynamic GetProducts4JqGrid1(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
4-why i Must pass the Entity ID to the controller ? I tried many other ways and it always come back as "0" so must pass the Id to the Put method , is this the only way ?
JQGrid is awesome with Web Api
nice to have everything under one roof
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using RoboMVC.Contracts;
using RoboMVC.Model;
namespace RoboMVC.Web.Controllers.jQgrid
{
public class ProductsJQgridController : ApiControllerBase
{
public ProductsJQgridController(IRoboMVCUow uow)
{
Uow = uow;
}
public dynamic GetProducts4JqGrid(string sidx, string sord, int page, int rows)
{
//var products = Uow.Product.GetAllProducts().OrderBy(e => e.ProductId) as IEnumerable<Product>;
var pageIndex = Convert.ToInt32(page) - 1;
var pageSize = rows;
var totalRecords = Uow.Product.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var products = Uow.Product.GetAllProducts().OrderBy(e => e.ProductId).Skip(pageIndex * pageSize).Take(pageSize) as IEnumerable<Product>;
return new
{
total = totalPages,
page = page,
records = totalRecords,
rows =
(
from product in products
select new
{
id = product.ProductId,
cell = new object[]
{
product.ProductId,
product.Description,
product.SalePrice,
product.SaleCommissionFactor,
product.Stock,
product.StockMax,
product.StockMin,
product.DateOfEntry,
product.LastDateOfSale,
product.SKU,
product.LastCostPaid,
product.Weight,
product.Image,
product.Categoy,
}
}).ToList()
};
}
public HttpResponseMessage Put( int id, Product product)
{
product.ProductId = Convert.ToInt32(id);
Uow.Product.Update(product);
Uow.Commit();
var result = new HttpResponseMessage(HttpStatusCode.NoContent);
return result;
}
public HttpResponseMessage Post(int id, Product product)
{
product.ProductId = Convert.ToInt32(id);
product = Uow.Product.Add(product);
Uow.Commit();
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, product);
string uri = Url.Route(null, new { id = product.ProductId });
response.Headers.Location = new Uri(Request.RequestUri, uri);
return response;
}
public HttpResponseMessage Delete(int id)
{
Uow.Product.Delete(id);
Uow.Commit();
var result = new HttpResponseMessage(HttpStatusCode.NoContent);
return result;
}
}
}
<script>
var API_URL = "/api/ProductsJQgrid/";
jQuery("#gridMain").jqGrid({
//http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
url: "/api/ProductsJQgrid/GetProducts4JqGrid/",
datatype: 'json',
mtype: 'GET',
pager: '#pagernav',
viewrecords: true,
height: '60%',
width: '100%',
hoverrows: true,
rownumbers: true,
shrinkToFit: true,
gridview: true,
search: true,
ignoreCase:true,
loadonce: false,
viewsortcols: [false, "horizontal", true],
imgpath: '../../Content/jquery.jqGrid/content/images/',
rowNum: 10,
cache: true,
rowList: [10, 20, 30],
sortable: true,
sortname: 'productId',
sortorder: "desc",
// sorttype: "text",
caption: "CRUD With ASP.NET Web API",
autowidth: true,
colNames: ['productId', 'Description', 'SalePrice', 'SaleCommissionFactor', 'Stock', 'StockMax', 'StockMin', 'DateOfEntry', 'LastDateOfSale', 'SKU', 'LastCostPaid', 'Weight', '<image src=images/arrow-right.gif width=16 height=16>', 'Categoy'],
colModel: [
//http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options
{ key:true, name: 'productId', index: 'productId', width: 40, search : true , sorttype: "int", editable: false },
{ name: 'description', index: 'description', editable: true, edittype: 'text', width: 70 },
{ name: 'salePrice', index: 'salePrice', editable: true, edittype: 'text', width: 50, align: "right", sorttype: "float", formatter: "number" },
{ name: 'saleCommissionFactor', index: 'saleCommissionFactor', editable: true, edittype: 'text', width: 50, align: "right", sorttype: "float", formatter: "number" },
{ name: 'stock', index: 'stock', editable: true, edittype: 'text', width: 50, align: "right", sorttype: "int" },
{ name: 'stockMax', index: 'stockMax', editable: true, cellEdit:true, edittype: 'text', width: 50, align: "right", sorttype: "int"},
{ name: 'stockMin', index: 'stockMin', editable: true, edittype: 'text', width: 50, align: "right", sorttype: "int"},
{ name: 'dateOfEntry', index: 'dateOfEntry', editable: true, edittype: 'text', width: 50, align: "right", sorttype: "date", formatter: "date" },
{ name: 'lastDateOfSale', index: 'lastDateOfSale', editable: true, edittype: 'text', width: 50, align: "right", sorttype: "date", formatter: "date" },
{ name: 'sKU', index: 'sKU', editable: true, edittype: 'text', width: 70 },
{ name: 'lastCostPaid', index: 'lastCostPaid', editable: true, edittype: 'text', width: 50, align: "right", sorttype: "float", formatter: "number" },
{ name: 'weight', index: 'weight', editable: true, edittype: 'text', width: 70 },
{ name: 'image', index: 'image', editable: false, search:false, width: 50, align: "right", },
{ name: 'categoy', index: 'categoy', editable: true, edittype: 'text', width: 70 }
],
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
id: "id", // from the controller returned value
cell: "cell",
search: "_search"
},
subGrid: true
});
function updateDialog(action) {
return {
url: "/api/ProductsJQgrid/"
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) { }
, modal: true
, onclickSubmit: function (params) {
var list = $("#gridMain");
var selectedRow = list.getGridParam("selrow");
var rowData = list.getRowData(selectedRow);
params.mtype = action;
params.url += rowData.productId;
debugger;
// image has the right data here
}
, width: "600"
};
}
jQuery("#gridMain")
.jqGrid('navGrid', '#pagernav',
{ add: true, edit: true, del: true, search: true,refresh: true },
updateDialog('Put'),
updateDialog('Post'),
updateDialog('Delete'),
{ sopt: ["cn"] } // Search options. Some options can be set on column level
)
// .filterToolbar({ autoSearch: false, searchOnEnter: false, stringResult: true })
;
$(window).bind('resize', function () {
jQuery("#gridMain").setGridWidth($('#parentDiv').width() - 30, true);
}).trigger('resize');
</script>

JQGrid Sorting is not working - MVC3

I am trying to sort the each columns in my JQGrid but its not working. Please refer my code below and help me
//View Code
$("#JQGridID").jqGrid({
url: '/Control/ActionResult/',
datatype: 'json',
mtype: 'POST',
colNames: ['Number', 'Unit'],
colModel: [
{ name: 'NNumber', index: 'Number', align: 'left', sortable: true, sorttype: 'int' },
{ name: 'NUnit', index: 'Unit', align: 'Center', sortable: true }
], pager: jQuery('#pager'),
cmTemplate: { title: false },
width: widthValue - 15,
height: 435,
rowNum: 20,
rowList: [20, 30, 40, 50, 60],
viewrecords: true,
gridComplete: loadCompleteFunction,
altRows: true,
sortorder: 'desc',
sortname: 'Number',
sortable: true,
onSortCol: function (index, idxcol, sortorder) {
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
}
}
,
onSelectRow: showMessageDetails,
postData: {
},
loadError: function (xml) { alert('Unable to load result data.'); }
});
//Control code
[HttpPost]
public ActionResult GetSearchPositionResult(string sidx, string sord, int page, int rows)
{
_Object = new PositionModel();
_Object.CurrentPage = page;
_Object.PageRowCount = rows;
_Object.load();
var result = new
{
total = _Object.TotalPages,
page = page,
sort = sidx,
sord = sord,
records = _Object.TotalRows,
rows = _ObjectPM.SearchResult.Select(p => new
{
cell = new string[]{
p.Number,
p.Unit
},sidx
}).OrderBy(a => a.sidx).ToArray(), };
return Json(result, JsonRequestBehavior.AllowGet);
}
In case of datatype: 'json' the sorting of data (sortable: true in colModel) is not handled on client-side by jqGrid but it has to be handled on server-side by your code. In another words you need to sort your _Object.SearchResult by the column name which you will receive in sidx parameter (the sorting direction is passed in sord parameter).
Here you can find a sample project which can help with using jqGrid in ASP.NET MVC: jqGrid in ASP.NET MVC 3 and Razor

Resources