jQgrid Search option is not working as expected - c#

I implement jQgrid free version in my MVC4 application.
Controller
public class HomeController : Controller
{
public ActionResult GridAction()
{
return View();
}
public JsonResult FillGrid(string sidx, string sord, int page, int rows)
{
var models = new List<Master> {
new Master { Id = 1, Name = "AAA",Description = "test description 1", Created = DateTime.Now },
new Master { Id = 2, Name = "BBB",Description = "test description 2", Created = DateTime.Now },
new Master { Id = 3, Name = "CCC",Description = "test description 3", Created = DateTime.Now },
new Master { Id = 4, Name = "DDD",Description = "test description 4", Created = DateTime.Now },
new Master { Id = 5, Name = "EEE",Description = "test description 5", Created = DateTime.Now },
new Master { Id = 6, Name = "FFF",Description = "test description 6", Created = DateTime.Now },
new Master { Id = 7, Name = "GGG",Description = "test description 7", Created = DateTime.Now },
new Master { Id = 8, Name = "HHH",Description = "test description 8", Created = DateTime.Now },
new Master { Id = 9, Name = "III",Description = "test description 9", Created = DateTime.Now },
new Master { Id = 10, Name = "JJJ",Description = "test description 10", Created = DateTime.Now },
new Master { Id = 11, Name = "KKK",Description = "test description 11", Created = DateTime.Now },
new Master { Id = 12, Name = "LLL",Description = "test description 12", Created = DateTime.Now },
new Master { Id = 13, Name = "MMM",Description = "test description 13", Created = DateTime.Now },
new Master { Id = 14, Name = "NNN",Description = "test description 14", Created = DateTime.Now },
new Master { Id = 15, Name = "OOO",Description = "test description 15", Created = DateTime.Now },
new Master { Id = 16, Name = "PPP",Description = "test description 16", Created = DateTime.Now },
new Master { Id = 17, Name = "QQQ",Description = "test description 17", Created = DateTime.Now },
new Master { Id = 18, Name = "RRR",Description = "test description 18", Created = DateTime.Now },
new Master { Id = 19, Name = "SSS",Description = "test description 19", Created = DateTime.Now },
new Master { Id = 20, Name = "TTT",Description = "test description 20", Created = DateTime.Now },
new Master { Id = 21, Name = "UUU",Description = "test description 21", Created = DateTime.Now },
new Master { Id = 22, Name = "VVV",Description = "test description 22", Created = DateTime.Now },
new Master { Id = 23, Name = "WWW",Description = "test description 23", Created = DateTime.Now },
new Master { Id = 24, Name = "XXX",Description = "test description 24", Created = DateTime.Now },
new Master { Id = 25, Name = "YYY",Description = "test description 25", Created = DateTime.Now },
new Master { Id = 26, Name = "ZZZ",Description = "test description 26", Created = DateTime.Now },
};
return Json((
from master in models
orderby master.Id descending
select new[] {
master.Id.ToString(CultureInfo.InvariantCulture),
master.Name,
master.Description,
master.Created == null ? "" : ((DateTime)master.Created).ToString("o")
}
).ToArray(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Add(string Name, string Description)
{
int ret = 2;
return Json(ret);
}
[HttpPost]
public ActionResult Update(string Name, string Description)
{
int ret = 2;
return Json(ret);
}
[HttpPost]
public ActionResult Delete(int Id)
{
int ret = 2;
return Json(ret);
}
[HttpPost]
public ActionResult Search()
{
return Json(1);
}
}
.cshtml
#{
ViewBag.Title = "GridAction";
}
<h2>GridAction</h2>
<table id="jQGridDemo">
</table>
<div id="jQGridDemoPager">
</div>
<table id="search"></table>
<div id="filter"></div>
<script type="text/javascript">
jQuery("#jQGridDemo").jqGrid({
url: '#Url.Action("FillGrid", "Home")',
datatype: "json",
mtype: "POST",
colNames: ["Id", "Name", "Description", "Created"],
colModel: [
{ name: "Id", width: 100, key: true, formatter: "integer", sorttype: "integer", hidden: true },
{ name: "Name", width: 200, sortable: true, editable: true, editrules: { required: true } },
{ name: "Description", width: 400, sortable: false, editable: true, editrules: { required: true } },
{ name: "Created", width: 120, formatter: "date", formatoptions: { srcformat: "ISO8601Long", newformat: "n/j/Y g:i:s A" }, align: "center", sorttype: "date" },
],
loadtext: "Loading...",
rowNum: 10,
gridview: true,
autoencode: true,
loadonce: true,
height: "auto",
rownumbers: true,
prmNames: { id: "Id" },
rowList: [10, 20, 30],
pager: '#jQGridDemoPager',
sortname: 'id',
sortorder: "asc",
viewrecords: true,
caption: "CRUD on Local Data",
editurl: '#Url.Action("Update", "Home")',
});
jQuery("#jQGridDemo").jqGrid('navGrid', '#jQGridDemoPager',
{
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
},
{//EDIT
url: '#Url.Action("Update", "Home")',
width: "auto",
jqModal: true,
closeOnEscape: true,
closeAfterEdit: true,
},
{//ADD
width: "auto",
// height: "auto"
url: '#Url.Action("Add", "Home")',
closeOnEscape: true,
closeAfterAdd: true
},
{//DELETE
url: '#Url.Action("Delete", "Home")',
closeOnEscape: true
},
{//SEARCH
closeOnEscape: true,
searchOnEnter: true,
});
jQuery("#jQGridDemo").jqGrid('searchGrid', {multipleSearch :true, caption: "Test caption" });
</script>
Add, Edit and Delete functions are works correctly in the toolbar. I implement the search option in the grid footer. When I click the search button, search option is appear correctly but the grid is not filtered correctly.

I suppose that the error exist because of including jQuery more as once. First you includes jQuery with respect of <script src="~/Scripts/jquery-1.9.1.min.js"></script>, then you includes jqGrid with respect of <script src="~/Scripts/jquery.jqGrid.src.js"></script>. It defines $.jgrid, jQuery.jgrid and other. After all you includes jQuery once more time as bundle with respect of #Scripts.Render("~/bundles/jquery"). It overwrites jQuery.jgrid, but not $.jgrid. During local searching or filtering the syntax jQuery.jgrid will be used and to jQuery.jgrid will be undefined and one will have exception in jQuery.jgrid.getAccessor.
To fix the problem you should include jQuery once. Just comment #Scripts.Render("~/bundles/jquery") if you use if after grid.locale-en.js and jquery.jqGrid.src.js. Ine should include <script src="~/Scripts/i18n/grid.locale-en.js"></script> and <script src="~/Scripts/jquery.jqGrid.src.js"></script> after jQuery.

Related

Issue in Binding jqGrid from controller ASP.Net MVC 5

My problem is very similar to this issue. I tried the solution he suggested but no luck.
If I remove the serialization then I got error saying:
a circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'
If I serialize the data then I get an empty grid. I'm using jQuery grid to bind a DataTable in my application.
public ActionResult FetchData(string item)
{
Repository o = new Repository();
DataTable dt = new DataTable();
dtEDIs = o.GetData(item);
JsonSerializerSettings jss = new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
var result = JsonConvert.SerializeObject(dtEDIs, Formatting.Indented, jss);
var jsonData = new
{
total = 10,
page = 1,
records = dt.Rows.Count,
rows = result
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
<table id="jQGridDemo"></table>
$("#jQGridDemo").jqGrid({
url: '/MyController/MyAction',
datatype: 'json',
mtype: 'get',
postData: {
itemNo: itemNo
},
colNames: ['ITEMNO', 'LOC', 'REQDATE'],
colModel: [{
name: "ItemNo"
}, {
name: "LOC"
}, {
name: "REQDATE"
}],
height: '100%',
rowNum: 10,
viewrecords: true,
caption: 'JQgrid',
emptyrecords: 'No records',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
});

How to fetch data into a DataTable using asp.net mvc?

I want to fetch data from server into a datatable in asp.net mvc5. I have my own datatable template which I want to customize but I couldn't fetch the data. The ajax call plus datatable itself is like below:
var DatatableRemoteAjaxDemo = function() {
//== Private functions
// basic demo
var demo = function() {
var datatable = $('.m_datatable').mDatatable({
// datasource definition
data: {
type: 'remote',
source: {
read: {
// sample GET method
method: 'GET',
url: '/ActionLinks/getActionLinks',
map: function(raw) {
// sample data mapping
var dataSet = raw;
if (typeof raw.data !== 'undefined') {
dataSet = raw.data;
}
return dataSet;
},
},
},
pageSize: 10,
saveState: {
cookie: true,
webstorage: true,
},
serverPaging: true,
serverFiltering: true,
serverSorting: true,
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed.
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
toolbar: {
// toolbar items
items: {
// pagination
pagination: {
// page size select
pageSizeSelect: [10, 20, 30, 50, 100],
},
},
},
search: {
input: $('#generalSearch'),
},
// columns definition
columns: [
{
field: 'ActionLinkId',
title: '#',
sortable: false, // disable sort for this column
width: 40,
selector: false,
textAlign: 'center',
}, {
field: 'ActionText',
title: 'Quiz Title',
// sortable: 'asc', // default sort
filterable: false, // disable or enable filtering
width: 150,
}, {
field: 'ActionDescription',
title: 'Quiz Description',
width: 150,
}, {
field: 'Category',
title: 'Category',
}, {
field: 'SmallImageURL',
title: 'Small Image URL',
width: 100,
}, {
field: 'LargeImageURL',
title: 'Large IMG URL',
width: 100,
},{
field: 'DateCreated',
title: 'CreationDate',
sortable: 'asc',
type: 'date',
format: 'MM/DD/YYYY',
}],
});
var query = datatable.getDataSourceQuery();
$('#m_form_status').on('change', function() {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Status = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Status !== 'undefined' ? query.Status : '');
$('#m_form_type').on('change', function() {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Type = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Type !== 'undefined' ? query.Type : '');
$('#m_form_status, #m_form_type').selectpicker();
};
return {
// public functions
init: function() {
demo();
},
};
}();
jQuery(document).ready(function() {
DatatableRemoteAjaxDemo.init();
});
My JsonResult code to fetch data from database is like below:
public JsonResult getActionLinks()
{
var actionlinks = db.ActionLinks.OrderBy(i => i.ActionLinkId).ToList();
return Json(new { data = actionlinks }, JsonRequestBehavior.AllowGet);
}
I debugged it the call hits the URL but I can't fetch the data into my datatable. It says 304 error. Please help.

How to display indirect data in Jqgrid

I am implementing Jqgrid in my ASP.net MVC web application. I have data some thing like this:
SID SNAME CITY
1 ABC 11
2 XYZ 12
3 ACX 13
4 KHG 14
5 ADF 15
6 KKR 16
and another table
CID CNAME
11 Chennai
12 Mumbai
13 Delhi like this
but, in the grid i would like to display like this:
SID SNAME City
1 ABC Chennai
2 XYZ Mumbai
3 ACX Delhi
4 KHG Banglore
5 ADF Hyderabad
6 KKR Kolkatta
I was not able to use join because the class structure is like this:
Class Student
{
long sid,
string sname,
long city
}
So, when i am reading from the data base i am getting the city id not city name.
But, i would like to display city name instead of City ID in the grid data to end user
i need some thing like a lookup function so that before binding data to the jQgrid,the city id will be mapped with city name and displays it instead of displaying ID
I didnt find a way to get this done.
Please help..
The controller method i am using is as follows:
public JsonResult Students()
{
List<Students> liStudents = new List<Students>();
SortedList<long, string> slLocations = new SortedList<long, string>();
slLocations = Students.LoadLocations();
liStudents = Students.GetStudents();
return Json(liStudents,JsonRequestBehavior.AllowGet);
}
How to modify the return statement to throw slLocations too in the json response
I answered already on the closed question before (see here). Nevertheless I decide to answer on your question in detail because the problem which you describe is really very common.
I start with reminding that jqGrid provides formatter: "select" which uses formatoptions.value or editoptions.value to decode ids to texts. The formatter: "select" uses value and optional separator, delimiter and defaultValue properties, but it can't uses editoptions.dataUrl to get required data from the server instead of usage static value. The problem is very easy: processing dataUrl works asynchronous, but during formatting of the column of grid body one don't support delayed filling. So to use formatter: "select" one have to set formatoptions.value or editoptions.value before the server response will be processed by jqGrid.
In the old answer I suggested to extend JSON response returned from the server with additional data for editoptions.value of the columns having formatter: "select". I suggest to set the beforeProcessing. For example one can generate the server response in the following format:
{
"cityMap": {"11": "Chennai", "12": "Mumbai", "13": "Delhi"},
"rows": [
{ "SID": "1", "SNAME": "ABC", "CITY": "11" },
{ "SID": "2", "SNAME": "XYZ", "CITY": "12" },
{ "SID": "3", "SNAME": "ACX", "CITY": "13" },
{ "SID": "4", "SNAME": "KHG", "CITY": "13" },
{ "SID": "5", "SNAME": "ADF", "CITY": "12" },
{ "SID": "6", "SNAME": "KKR", "CITY": "11" }
]
}
and uses the following jqGrid options
colModel: [
{name: "SNAME", width: 250},
{name: "CITY", width: 180, align: "center"}
],
beforeProcessing: function (response) {
var $self = $(this);
$self.jqGrid("setColProp", "CITY", {
formatter: "select",
edittype: "select",
editoptions: {
value: $.isPlainObject(response.cityMap) ? response.cityMap : []
}
});
},
jsonReader: { id: "SID"}
The demo demonstrates the approach. It displays
One can use the same approach to set any column options dynamically. For example one can use
{
"colModelOptions": {
"CITY": {
"formatter": "select",
"edittype": "select",
"editoptions": {
"value": "11:Chennai;13:Delhi;12:Mumbai"
},
"stype": "select",
"searchoptions": {
"sopt": [ "eq", "ne" ],
"value": ":Any;11:Chennai;13:Delhi;12:Mumbai"
}
}
},
"rows": [
{ "SID": "1", "SNAME": "ABC", "CITY": "11" },
{ "SID": "2", "SNAME": "XYZ", "CITY": "12" },
{ "SID": "3", "SNAME": "ACX", "CITY": "13" },
{ "SID": "4", "SNAME": "KHG", "CITY": "13" },
{ "SID": "5", "SNAME": "ADF", "CITY": "12" },
{ "SID": "6", "SNAME": "KKR", "CITY": "11" }
]
}
and the following JavaScript code
var filterToolbarOptions = {defaultSearch: "cn", stringResult: true, searchOperators: true},
removeAnyOption = function ($form) {
var $self = $(this), $selects = $form.find("select.input-elm");
$selects.each(function () {
$(this).find("option[value='']").remove();
});
return true; // for beforeShowSearch only
},
$grid = $("#list");
$.extend($.jgrid.search, {
closeAfterSearch: true,
closeAfterReset: true,
overlay: 0,
recreateForm: true,
closeOnEscape: true,
afterChange: removeAnyOption,
beforeShowSearch: removeAnyOption
});
$grid.jqGrid({
colModel: [
{name: "SNAME", width: 250},
{name: "CITY", width: 180, align: "center"}
],
beforeProcessing: function (response) {
var $self = $(this), options = response.colModelOptions, p,
needRecreateSearchingToolbar = false;
if (options != null) {
for (p in options) {
if (options.hasOwnProperty(p)) {
$self.jqGrid("setColProp", p, options[p]);
if (this.ftoolbar) { // filter toolbar exist
needRecreateSearchingToolbar = true;
}
}
}
if (needRecreateSearchingToolbar) {
$self.jqGrid("destroyFilterToolbar");
$self.jqGrid("filterToolbar", filterToolbarOptions);
}
}
},
jsonReader: { id: "SID"}
});
$grid.jqGrid("navGrid", "#pager", {add: false, edit: false, del: false})
$grid.jqGrid("filterToolbar", filterToolbarOptions);
The demo uses the above code.
We recreate the searching filter if any option are changed dynamically. The way allows implement more flexible solutions. For example the server can detect the language preferences of the client (of the web browser) and return formatting options for numbers, dates and so on based on the options. I'm sure that everyone can suggest other interesting scenarios.
One more remark. If you have too many items in select in (searchoptions.value and editoptions.value) I would recommend you don't use strings instead of objects as the value of searchoptions.value and editoptions.value. It allows you to specify the order of items in the select element.
If you will have too many items in select (for example all cities of your country) then you can consider to use select2 plugin which usage I demonstrate in the answer. It simplify selection of options because it convert select in element which is very close to jQuery UI Autocomplete.
The next demo demonstrate the usage of select2 plugin. If one click on the dropdown arrow of "select" element of the searching toolbar or the searching dialog one get additional input filed which can be used for quick searching. If one starts to type some text in the input box (for example "e" on an example on the picture below) the list of options will be reduced to the options having the typed text as substring:
I personally find such "select-searching" control very practical.
By the way I described in the another answer how to set colNames dynamically. In can be used to manage more information from the server side.
UPDATED: The corresponding controller action Students can be about the following
public class Student {
public long SID { get; set; }
public string SNAME { get; set; }
public long CITY { get; set; }
}
public class City {
public long CID { get; set; }
public string CNAME { get; set; }
}
...
public class HomeController : Controller {
...
public JsonResult Students () {
var students = new List<Student> {
new Student { SID = 1, SNAME = "ABC", CITY = 11 },
new Student { SID = 2, SNAME = "ABC", CITY = 12 },
new Student { SID = 3, SNAME = "ABC", CITY = 13 },
new Student { SID = 4, SNAME = "ABC", CITY = 13 },
new Student { SID = 5, SNAME = "ABC", CITY = 12 },
new Student { SID = 6, SNAME = "ABC", CITY = 11 }
};
var locations = new List<City> {
new City { CID = 11, CNAME = "Chennai"},
new City { CID = 12, CNAME = "Mumbai"},
new City { CID = 13, CNAME = "Delhi"}
};
// sort and concatinate location corresponds to jqGrid editoptions.value format
var sortedLocations = locations.OrderBy(location => location.CNAME);
var sbLocations = new StringBuilder();
foreach (var sortedLocation in sortedLocations) {
sbLocations.Append(sortedLocation.CID);
sbLocations.Append(':');
sbLocations.Append(sortedLocation.CNAME);
sbLocations.Append(';');
}
if (sbLocations.Length > 0)
sbLocations.Length -= 1; // remove last ';'
return Json(new {
colModelOptions = new {
CITY = new {
formatter = "select",
edittype = "select",
editoptions = new {
value = sbLocations.ToString()
},
stype = "select",
searchoptions = new {
sopt = new[] { "eq", "ne" },
value = ":Any;" + sbLocations
}
}
},
rows = students
},
JsonRequestBehavior.AllowGet);
}
}
#Avinash, You can do some trick like this. But still it's not a better solution. It may help you get some idea. What my suggestion is you need to find out better way from your server(ASP.Net) itself. I used grid complete function to modify your data,
gridComplete: function () {
var rowIDs = jQuery("#list5").getDataIDs();
for (var i=0;i<rowIDs.length;i=i+1){
rowData=jQuery("#list5").getRowData(rowIDs[i]);
if (rowData.city == "11") {
$("#list5").find('td').eq('5').html('chennai');
}else if (rowData.city == "12") {
$("#list5").find('td').eq('8').html('mumbai');
}
}
}
Hope this helps.

No Data Shown On JQGrid

I'm fairly new to MVC and Jquery. for last couple of days I was trying to use Jqgrid http://www.trirand.com/blog/ to show data in my database. I use EF Code first to create my only class 'Author'
public class Author
{
public int AuthorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return FirstName+ " "+LastName ;
}
}
}
and this is my 'AuthorController' which create Json data:
public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 5,
page = 1,
records = db.Authors.Count(),
rows = db.Authors.Select(a => new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I also tried different method to get my Json data:
public ActionResult LinqGridData (string sidx, string sord, int page, int rows)
{
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = (from a in db.Authors
select new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and here is my JavaScript, which I use in my view:
$(function () {
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
mtype: 'GET',
colNames:['Author ID', 'First Name', 'Last Name'],
colModel:[
{name:'AuthorID',index:'AuthorID',width:55 },
{name:'FirstName',index:'FirstName',width:90 },
{name:'LastName',index:'LastName',width:80,align:'right' }
],
pager:'#pager',
rowNum: 10,
rowList:[5, 10, 20, 30],
sortname:'AuthorID',
sortorder:'desc',
viewrecords:true,
gridview:true,
caption:'Author List'
});
});
jQuery("#datagrid").jqGrid('navGrid', '#navGrid', { edit: true, add: true, del: true });
I can show the grid with dummy data. with this action method:
public ActionResult GridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 1, // we'll implement later
page = 1,
records = 3, // implement later
rows = new[]
{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is that a good question?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky in the sky?"}}
}
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
the problem is whenever I want to show the data from my database, I only can show the grid itself not the data.
I tried to convert the json data toList() or toArary() before sending to the view, same result. I hope I made myself clear.
any help would be much appreciated.
Have you tried jsonReader with "repeatitems: false" ?
For example:
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
jsonReader: {
repeatitems: false
},
.....
UPDATE:
If you look at the response body returned from your LinqGridData method, it looks like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"AuthorID":"1","FirstName":"Mike","LastName":"Lee"}}, .....
]
}
But I think it should be like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"1", "Mike", "Lee"}}, .....
]
}
Actually this is your "dummy data" version's response body.
I'll post my working example below. In this example, I did not use 'cell' attribute.
At server side:
var myQuery = from t in db.Customers
select t;
var jsonData = new
{
total = totalPages,
page = pageNum,
records = totalRecords,
rows = myQuery.ToList()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
At client side:
{
url: '#Url.Action("GetList")',
datatype: 'json',
jsonReader: {
repeatitems: false
},
mtype: 'GET',
colModel: [
{
name: 'CustomerID', label: 'ID', hidden: false, width: 40, sortable: true
},
{
name: 'CompanyName', label: 'Company', width: 100, align: 'center'
},
]
}
Hope this helps.
I finally managed to show data from my db. the problem was in my query. i use this method for my action method:
public JsonResult LinqGridData (string sidx, string sord, int page, object rows)
{
var authors = (from a in db.Authors select a).ToList();
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = authors.Select(a => new
{
id = a.AuthorID,
cell = new[] { a.AuthorID.ToString(), a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and i used this in my Javascript:
$(function () {
$("#list").jqGrid({
url: "/Author/LinqGridData",
datatype: "json",
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id:"id"
},
mtype: "GET",
colNames: ["Author ID", "First Name", "Last Name"],
colModel: [
{ name: "AuthorID", key: true, width: 55 },
{ name: "FirstName", width: 80 },
{ name: "LastName", width: 100, align: "right" }
],
pager: "#pager",
rowNum: 10,
rowList: [5, 10, 20],
sortname: "AuthorID",
sortorder: "desc",
viewrecords: true,
gridview: true,
width: 610,
height: 250,
caption: "Author List"
});
});
jQuery("#list").jqGrid("navGrid", "#pager", { edit: true, add: true, del: true });
yes , you can omit the 'cell' attribute and reduce your json data. you can also put 'id':0 which normally means treat the first item as the id. i also used 'key' attribute, but it's redundant. you can also pass your query result as Array too. if anyone can tell me is there any benefit of using List over others would much appreciated.
Thanks for your help
good luck

jqgrid mvc json format?

Script:
jQuery("#grid_table").jqGrid({
url: '#Url.Action("GetAll", "Widget")',
datatype: "json",
mtype: 'GET',
colNames: ['id', 'name'],
colModel: [
{ name: 'id', index: 'id', width: 55, sortable: true, editable: false, editoptions: { readonly: true, size: 10} },
{ name: 'name', index: 'name', width: 200, editable: true }
],
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "id",
userdata: "userdata"
},
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery('#gridpager'),
sortname: 'name',
viewrecords: true,
sortorder: "asc",
caption: "Wines"
}).navGrid('#gridpager');
Controller:
public ActionResult GetAll()
{
List<object> list = new List<object>();
for (int i = 0; i < 20; i++)
{
var o = new
{
id = i.ToString(),
name = "name " + i.ToString()
};
list.Add(o);
}
var result = new
{
page = "1",
total = "1",
records = "10",
rows = list.ToArray()
};
string Jlist = Newtonsoft.Json.JsonConvert.SerializeObject(result);
return Json(Jlist, JsonRequestBehavior.AllowGet);
}
Json output:
And message: No records found!
What is the wrong with my code?
Thanks.
I think as mentioned in your json reader "userdata" is not there in your json .
So please pass some null value or any value in your userdata field.
Problem is this line:
string Jlist = Newtonsoft.Json.JsonConvert.SerializeObject(result);
I removed serilization line and then it works. Thanks for reply.

Categories