jqgrid retrieving empty rows using webapi (REST) - jqgrid

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.

Related

Jqgrid cascading dropdown

Using jqgrid free latest version 4.15.2
I am trying to make cascading drop down from db.
I tried the sample as posted by #Oleg
jqgrid incorrect select drop down option values in edit box
But this is for older version of jqgrid and does not work fully while using latest version of jqgrid.
var countries = { "UsId": "US", "UkId": "UK" },
statesOfUS = { "AlabamaId": "Alabama", "CaliforniaId": "California", "FloridaId": "Florida", "HawaiiId": "Hawaii" },
statesOfUK = { "LondonId": "London", "OxfordId": "Oxford" },
states = $.extend({}, statesOfUS, statesOfUK),
allCountries = $.extend({"": "All"}, countries),
allStates = $.extend({"": "All"}, states),
// the next maps provide the states by ids to the contries
statesOfCountry = {
"": states,
"UsId": statesOfUS,
"UkId": statesOfUK
},
The entire code can be seen in fiddle below
https://jsfiddle.net/svnL4Lsv/
The issue is during the add form the second dropwdown shows all states instead of showing as per country
Secondly during the edit the second dropdown again shows all states and not as per the row value
Its just when I change the first dropdown does the second dropdown filters and works.
----------Updated
editoptions: {
// value: countries,
dataInit: dataInitApp,
dataEvents: dataEventsApp,
dataUrl: '#Url.Action("GetData", "Home")',
}
Controller code:
public enum Countries
{
USA = 1,
UK = 2
}
public enum State
{
Alabama = 1,
Florida = 2
London = 3
}
public JsonResult GetData()
{
var type = typeof(Helpers.UsersEnum.Countries);
var jsonData = Enum.GetNames(type)
.Select(name => new
{
Id = (int)Enum.Parse(type, name),
Name = name
})
.ToArray();
return Json(jsonData);
}
I call the above to populate my dropdown.
Also below is the json that is returned back:
[0]: {Id=1, Name="USA"}
[1]: {Id=2, Name="UK"}
[0]: {Id=1, Name="Alabama "}
[1]: {Id=2, Name="Florida"}
[2]: {Id=3, Name="London"}
In case of usage free jqGrid you can use a little simplified code
$(function () {
"use strict";
var countries = "usId:US;ukId:UK",
allStates = "alabamaId:Alabama;californiaId:California;floridaId:Florida;hawaiiId:Hawaii;londonId:London;oxfordId:Oxford",
// the next maps provide the states by ids to the countries
statesOfCountry = {
"": allStates,
usId: "alabamaId:Alabama;californiaId:California;floridaId:Florida;hawaiiId:Hawaii",
ukId: "londonId:London;oxfordId:Oxford"
},
mydata = [
{ id: "10", country: "usId", state: "alabamaId", name: "Louise Fletcher" },
{ id: "20", country: "usId", state: "floridaId", name: "Jim Morrison" },
{ id: "30", country: "ukId", state: "londonId", name: "Sherlock Holmes" },
{ id: "40", country: "ukId", state: "oxfordId", name: "Oscar Wilde" }
],
$grid = $("#list"),
changeStateSelect = function (countryId, countryElem) {
// build "state" options based on the selected "country" value
var $select, selectedValues,
$countryElem = $(countryElem),
isInSearchToolbar = $countryElem.parent().parent().parent().parent().hasClass("ui-search-table");
// populate the subset of countries
if (isInSearchToolbar) {
// searching toolbar
$select = $countryElem.closest("tr.ui-search-toolbar")
.find(">th.ui-th-column select#gs_list_state");
} else if ($countryElem.is(".FormElement")) {
// form editing
$select = $countryElem.closest("form.FormGrid")
.find("select#state.FormElement");
} else {
// inline editing
$select = $("select#" + $.jgrid.jqID($countryElem.closest("tr.jqgrow").attr("id")) + "_state");
}
if ($select.length > 0) {
selectedValues = $select.val();
if (isInSearchToolbar) {
$select.html("<option value=\"\">All</option>");
} else {
$select.empty();
}
$.jgrid.fillSelectOptions($select[0], statesOfCountry[countryId], ":", ";", false, selectedValues);
}
},
dataInitCountry = function (elem) {
setTimeout(function () {
$(elem).change();
}, 0);
},
dataEventsCountry = [
{ type: "change", fn: function (e) { changeStateSelect($(e.target).val(), e.target); } },
{ type: "keyup", fn: function (e) { $(e.target).trigger("change"); } }
],
cancelInlineEditingOfOtherRows = function (rowid) {
var $self = $(this), savedRows = $self.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0 && rowid !== savedRows[0].id) {
$self.jqGrid("restoreRow", savedRows[0].id);
}
};
$grid.jqGrid({
data: mydata,
datatype: "local",
colNames: [ "Name", "Country", "State" ],
colModel: [
{ name: "name", width: 180 },
{ name: "country", formatter: "select", stype: "select", edittype: "select",
searchoptions: {
noFilterText: "Any",
dataInit: dataInitCountry,
dataEvents: dataEventsCountry
},
editoptions: {
value: countries,
dataInit: dataInitCountry,
dataEvents: dataEventsCountry
}},
{ name: "state", formatter: "select", stype: "select", edittype: "select",
editoptions: { value: allStates }, searchoptions: { noFilterText: "Any" } }
],
cmTemplate: { width: 100, editable: true },
onSelectRow: cancelInlineEditingOfOtherRows,
ondblClickRow: function (rowid) {
cancelInlineEditingOfOtherRows.call(this, rowid);
$(this).jqGrid("editRow", rowid);
},
inlineEditing: {
keys: true
},
formEditing: {
onclickPgButtons: function (whichButton, $form, rowid) {
var $self = $(this), $row = $($self.jqGrid("getGridRowById", rowid)), countryId;
if (whichButton === "next") {
$row = $row.next();
} else if (whichButton === "prev") {
$row = $row.prev();
}
if ($row.length > 0) {
countryId = $self.jqGrid("getCell", $row.attr("id"), "country");
changeStateSelect(countryId, $form.find("#country")[0]);
}
},
closeOnEscape: true
},
searching: {
searchOnEnter: true,
defaultSearch: "cn"
},
navOptions: {
del: false,
search: false
},
iconSet: "fontAwesome",
sortname: "name",
sortorder: "desc",
viewrecords: true,
rownumbers: true,
pager: true,
pagerRightWidth: 85, // fix wrapping or right part of the pager
caption: "Demonstrate dependent selects (inline editing on double-click)"
})
.jqGrid("navGrid")
.jqGrid("filterToolbar");
});
see https://jsfiddle.net/OlegKi/svnL4Lsv/3/

JqGrid MVC post data is not working

I am trying to pass some values from jQGrid to controller of my MVC application. The grid was displaying properly but no data was showing.
My code is below
Ajax
function LoadGrid(varLocationID) {
var jqDataUrl = null;
jqDataUrl = "ManageRoutes/ManageRoutes" //+ x;
var Location = varLocationID.getAttribute('value');
var grid = $("#grid").grid({
url: "/ManageRoutes/GetRoutes/",
postData: { "szLocationID": function () { return Location; } },
cache: false,
datatype: "json",
mtype: "POST",
// Specify the column names
colNames: ["RouteID", "CompanyID", "LocationID", "SalesManCode", "SalesManName"],
// Configure the columns
colModel: [
{ name: "RouteID", index: "RouteID", width: 70, align: "left" },
{ name: "CompanyID", index: "CompanyID", width: 200, align: "left" },
{ name: "LocationID", index: "LocationID", width: 200, align: "left" },
{ name: "SalesManCode", index: "SalesManCode", width: 150, align: "left" },
{ name: "SalesManName", index: "SalesManName", width: 170, align: "left" }
],
pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] }
});
and code in controller
[HttpPost]
public JsonResult GetRoutes(string szLocationID)
{
List<RouteNames> qry = new List<RouteNames>();
using (TESTEntities1 dc = new TESTEntities1())
{
qry = (from s in dc.t_hhc_dnl_Route_ID.AsEnumerable()
select new RouteNames
{
CompanyID = s.CompanyID,
LocationID = s.LocationID ,
RouteID = s.RouteID,
SalesManCode=s.SalesManCode ,
SalesManName = s.SalesManName
}).Where(m => m.LocationID.Contains(szLocationID)).Take(100).ToList();
}
var jsonData = new
{
data = from emp in qry select emp
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Any help would be appreciated.
Changed as below code and got worked ..
"ajax": {
"url": "/ManageRoutes/GetRoutes",
"type": "POST",
"data": function (d) {
d.szLocationID = Location;
}

jqgrid inline editing autocomplete dropdown

Found answers in Oleg post but unable to solve in my case.
I have a jqGrid with inline editing. That works fine. One column 'SupervisorUserID' has a dropdown box with list of entries which retrieved from a database query already.
As the entries are too much, I want to have an input field which will autocomplete/search the dropdown list.
Please help me to achieve this. Thanks.
My code,
public JsonResult PersonnelManagementGrid(string sidx, string sord, int page, int rows)
{
objPersonnelManagementViewModel = new PersonnelManagementViewModel();
objPersonnelManagementViewModel.PersonnelManagementModelList = (List<PersonnelManagementModel>) Session["PersonnelList"];
var results = objPersonnelManagementViewModel.PersonnelManagementModelList.Select(x => new
{
x.UserID,
x.Name,
x.InActive,
x.SupervisorUserID,
});
int pageIndex = Convert.ToInt16(page) - 1;
int pageSize = rows;
int totalRecords = results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{ results = results.OrderByDescending(e => e.Name); }
else { results = results.OrderBy(e => e.Name); }
results = results.Skip(pageIndex * pageSize).Take(pageSize);
var sbLocations = new System.Text.StringBuilder();
Dictionary<string, string> personnelList = new Dictionary<string, string>();
personnelList = objPersonnelManagementViewModel.PersonnelManagementModelList.ToDictionary(x => x.UserID, x => x.Name);
//personnelList.Add("1","one");
//personnelList.Add("2", "two");
//personnelList.Add("3", "three");
foreach (var sortedLocation in personnelList)
{
sbLocations.Append(sortedLocation.Key);
sbLocations.Append(':');
sbLocations.Append(sortedLocation.Value);
sbLocations.Append(';');
}
if (sbLocations.Length > 0)
sbLocations.Length -= 1; // remove last ';'
var jsonResults = new
{
colModelOptions = new
{
SupervisorUserID = new
{
formatter = "select",
edittype = "select",
editoptions = new
{
value = sbLocations.ToString()
}
}
},
total = totalPages,
page,
records = totalRecords,
rows= results,
};
return Json(jsonResults, JsonRequestBehavior.AllowGet);
}
Jquery:
$(function () {
$("#PersonnelManagementGrid").jqGrid({
url: '/PersonnelManagement/PersonnelManagementGrid',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'Get',
colNames: ['UserID', 'Name', 'Role', 'Active?', 'Supervisor', 'Change Active', 'Try Delete'],
colModel: [
{ key: true, name: 'UserID', index: 'UserID', hidden: true },
{
name: 'Name', index: 'Name', editable: false, width: "460", sortable: true,
},
{
name: 'Role', index: 'Role', editable: false, width: "200", sortable: true,
},
{
name: 'InActive', index: 'InActive', editable: false, width: "200", sortable: true,
},
{
name: 'SupervisorUserID', index: 'SupervisorUserID', editable: true, formatter: 'select', width: "200", sortable: true,
edittype: 'select', width: "200", align: "center",
},
{
name: "Change Active", sortable: false, width: "200", align: "center",
formatter: function (cellvalue, options, rowObj) {
var cBtn = '<input type="button" class="button" value="Change" onclick= "changeActive(' + "'" + rowObj.id + "','" + "values" + "','" + "values" + '\')"/>'
return cBtn;
}
},
{
name: "Try Delete", sortable: false, width: "200", align: "center",
formatter: function (cellvalue, options, rowObj) {
var cBtn = '<input type="button" value="Delete" onclick= "tryDelete(' + "'" + rowObj.id + "','" + "values" + "','" + "values" + '\')"/>'
return cBtn;
}
}
],
beforeProcessing: function (response) {
var $self = $(this),
options = response.colModelOptions, p;
if (options != null) {
for (p in options) {
if (options.hasOwnProperty(p)) {
$self.jqGrid("setColProp", p, options[p]);
}
}
}
},
pager: jQuery('#pager'),
rowNum: 15,
rowList: [5, 10, 15],
height: '100%',
width: '1328',
viewrecords: true,
caption: 'Personnel Management',
//loadonce: true,
emptyrecords: 'No records to display',
scrollerbar: false,
jsonReader: {
root: "rows",
page: "pagenumbers",
total: "totalnumbers",
records: "records",
repeatitems: false,
id: "0"
},
hidegrid: false,
multiselect: false,
onSelectRow: function (id) {
rowSelect(id);
},
}).navGrid('#pager', { edit: false, add: false, del: false, search: false, cancel: false, reload: false, refresh: false });
});

JQgrid Sorting MVC3

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

jqGrid Problem Binding Subgrid

I have a jqGrid that is not correctly displaying the subgrid rows. When I load the page, the regular grid rows display fine as well as the plus sign next to each of them, but when I click the plus button to expand them, the "Loading..." message just remains and nothing happens. I don't know if it makes a difference, but I am trying to do it on client side (loadonce: true).
Here is the code for creating the grid:
$("#Grid1").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: null,
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
datatype: function(postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'WebServices/GetJSONData.asmx/getGridData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data, st) {
if (st == "success") {
var grid = $("#Grid1")[0];
grid.addJSONData(JSON.parse(data.d));
//Loadonce doesn't work, have to do its dirty work
$('#Grid1').jqGrid('setGridParam', { datatype: 'local' });
//After rows are loaded, have to manually load subgrid rows
var subgridData = JSON.parse(data.d).subgrid;
var lista = jQuery("#Grid1").getDataIDs();
var rowData;
//Iterate over each row in grid
for (i = 0; i < lista.length; i++) {
//Get current row data
rowData = jQuery("#Grid1").getRowData(lista[i]);
}
}
},
error: function() {
alert("Error with AJAX callback");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id", //index of the column with the PK in it
userdata: "userdata",
repeatitems: true
},
coNames: ['Inv No', 'Amount', 'Store', 'Notes'],
colModel: [
{ name: 'InvNum', index: 'InvNum', width: 200 },
{ name: 'Amount', index: 'Amount', width: 55 },
{ name: 'Store', index: 'Store', width: 50 },
{ name: 'Notes', index: 'Notes', width: 100 }
],
subGrid: true,
subGridModel: [{
name: ['InvNum', 'Name', 'Qauntity'],
width: [55, 200, 80],
params: ['InvNum']
}],
rowNum: 10,
rowList: [10, 20, 50],
pager: '#Div1',
viewrecords: true,
width: 500,
height: 230,
scrollOffset: 0,
loadonce: true,
ignoreCase: true,
gridComplete: function() {
$(".loading").hide();
}
}).jqGrid('navGrid', '#Div1', { del: false, add: false, edit: false }, {}, {}, {}, { multipleSearch: true });
Here the code that I am using in the webservice call to create the JSON data:
IEnumerable orders = getOrders();
IEnumerable items = getItems();
int k = 0;
var jsonData = new
{
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row in orders
select new
{
id = k++,
cell = new string[] {
row.InvNum.ToString(), row.Amount.ToString(), row.Store, row.Notes
}
}
).ToArray(),
subgrid = (
from row in items
select new
{
cell = new string[] {
row.InvNum.ToString(), row.Name, row.Quantity.ToString()
}
}
).ToArray()
};
result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);

Resources