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.
Related
I am having issues with Free Jqgrid where I can not get it to post to my developer version of Microsoft SQL server. I am using Microsoft visual studios. I am using entity framework 6 for the database connections. When I use break points it doesn't seem to hit my createbid, editbid, or delete bid. I also don't get any errors in console.
I have looked through and done many of the tutorials for editing updating and adding lines. I had the same problem. I cant find an answer that works on stack overflow through my research.
I published it to IIS to see if maybe it was something with visual studios and to see if anything changes but i did get some errors this time. It is not finding the /Home/GetBidValues, Home/EditBid, /Home/CreateBid, /Home/DeleteBid. this is weird because with visual studios it was at least getting data into the grid and showing it. So I will look into this further and see if there is something wrong with my ajax and also with my C# code.
Here is my Jquery file
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['Client Cost', 'ElementId', 'Note', 'Area', 'Element', 'Item', 'Qty', 'Description'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
{
key: true,
hidden: true,
name: 'ElementId',
index: 'ElementId',
frozen: true,
editable: false
}, {
key: false,
name: 'Note',
index: 'Note',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Area',
index: 'Area',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Element',
index: 'Element',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
name: 'Item',
index: 'Item',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'QTY',
index: 'QTY',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Description',
index: 'Description',
frozen: true,
editable: true,
width: 70,
align: 'center'
}],
pager: '#pager',
gridview: true,
ignoreCase: true,
rowNumbers: false,
shrinkToFit: false,
height: '100%',
width: 1000,
viewrecords: true,
footerrow: true,
emptyrecords: 'No records to display',
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
}
});
$('#grid').jqGrid( 'inlineNav','#pager', {
edit: true,
add: true,
del: true,
cancel: true,
search: true,
refresh: true,
editparams: {
keys:true
}
}, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},{//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
Here is my C# file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ERPWebAppTest.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
namespace ERPWebAppTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
Test1Entities db = new Test1Entities();
[HttpGet]
public JsonResult GetBidValues(string sidx, string sord, int page, int rows)
{
//old code
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var Results = db.BidDetails.Select(
a => new
{
a.ElementID,
a.Note ,
a.Area ,
a.Element ,
a.Item ,
a.QTY ,
a.Descr ,
});
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string CreateBid([Bind(Exclude = "ElementID")] BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.BidDetails.Add(obj);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfully";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string EditBid(BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string DeleteBid(int ElementID)
{
Test1Entities db = new Test1Entities();
BidDetail list = db.BidDetails.Find(ElementID);
db.BidDetails.Remove(list);
db.SaveChanges();
return "Deleted successfully";
}
}
}
I see many small small issues into your jqgrid code, which can be one of the reason of your current problem. You can change them in order to make the above code workable.
colModel items numbers are not exactly same as colNames items. You wrote Client Cost at first in colNames but in colModel you haven't used that.
You also haven't pasted your html code which is required to point jqgrid to load on table element.
for example:
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
I am also assuming that you have already added free-jqgrid scripts and jquery-ui css files.
Also, in your c# code you can remove redundancy by using a global db initialization.
I have created a demo jqgrid which you can alter according your requirement:
<div class="row">
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
</div>
#section Scripts{
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/free-jqGrid/jquery.jqgrid.min.js"></script>
<script type="text/javascript">
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['LanguageId', 'LanguageName', 'LanguageDescription', 'CreatedBy', 'CreatedOn'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
//{ name: "act", template: "actions", align: "left", width: 58 },
{
key: true,
hidden: true,
name: 'LanguageId',
index: 'LanguageId',
editable: false
}, {
key: false,
name: 'LanguageName',
index: 'LanguageName',
frozen: true,
editable: true,
align: 'center'
}, {
key: false,
name: 'LanguageDescription',
index: 'LanguageDescription',
editable: true,
align: 'center'
}, {
key: false,
name: 'CreatedBy',
index: 'CreatedBy',
editable: true,
align: 'center'
}, {
name: 'CreatedOn',
index: 'CreatedOn',
editable: true,
align: 'center'
}],
//cmTemplate: { editable: true, autoResizable: true },
iconSet: "fontAwesome",
rowNum: 10,
//autoResizing: { compact: true },
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
pager: jQuery('#pager'),
toppager: false,
inlineEditing: { keys: true, position: "afterSelected" },
rownumbers: true,
sortname: "invdate",
sortorder: "desc",
caption: "Demonstration of the usage custom action buttons",
autowidth: true,
shrinkToFit: false,
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "LanguageId"
}
});
jQuery("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter:
false, defaultSearch: "cn", multipleSearch: true, searchOperators: true, search: true
}); //searchOnEnter: false means records are filtered as soon as the text is
entered by the user
jQuery("#grid").jqGrid('navGrid', '#pager', { add: true, edit: true, del: true, search: true, refresh: true,view:true }, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
</script>
}
I have a problem when using a CustomField ( Name() ) within a filter that is using ds.query in order to filter, sort and reinitialize the pager for a Grid, I have created a simplified example that illustrates the problem clearly: https://jsfiddle.net/juliemontreuil/4Ls4fb19/32/
var PageSize = 5;
var data1 = [...];
var $grid = $("#BTGrid");
var sort = [{
field: "company",
dir: "asc"
}];
var dataSource = new kendo.data.DataSource({
data: data1,
schema: {
model: {
id: "Id",
fields: {
Id: {},
Firstname: {},
LastName: {},
company: {},
email: {}
},
Name: function() {
return this.get("Firstname") + " " + this.get("LastName");
}
}
},
sort: sort,
pageSize: PageSize //page size
});
$grid.kendoGrid({
dataSource: dataSource,
columns: [{
field: "Name()",
title: "Name",
}, {
field: "company",
title: "Company"
}, {
field: "email",
title: "Email"
}],
scrollable: false,
pageable: true, //enable paging
resizable: true,
sortable: {
allowUnsort: false
}
});
$('.grid-filter').off('keyup').on('keyup', function() {
var ds = $("#BTGrid").data("kendoGrid").dataSource;
// debugger;
var filterText = $(this).val();
var $filter = {
logic: "or",
filters: [{
field: "company",
operator: "contains",
value: filterText
}, {
field: "email",
operator: "contains",
value: filterText
}, {
field: "Name()",
operator: "contains",
value: filterText
}]
};
ds.query({
filter: $filter,
sort: [{
field: "company",
dir: "asc"
}],
page: 1,
pageSize: PageSize
});
});
, if you modify the var PageSize = 5; to var PageSize = 25; the filter will function correctly because the data array contains only 24 items, please advise .
I have been testing your code and I note that the Name function is the one is failing.
So I made this for you:
Solution whitout Name()
Note that now the kendogrid use a template:
$grid.kendoGrid({
dataSource: dataSource,
columns: [{
title: "Name",
template: '#= Firstname# #= LastName#',
}, {
field: "company",
title: "Company"
}, {
field: "email",
title: "Email"
}],
scrollable: false,
pageable: true, //enable paging
resizable: true,
sortable: {
allowUnsort: false
}
});
..Yes,..of course,.. now you are going to say: "How cant filter by the full name (Firstname + Lastname)?".
Well, in order to fix that situation you can declare a property (FulName) inside "data1" and then use that property in the grid and inside the filter too.
Hope this ideas works for you. :)
I have a kendo grid that is edited inline. One of the fields should be edited selecting an element from a list, but the list must have a hierarchical structure (would be nice be able of filter that list). I was thinking in use a kendo treeview as editor for that field but I haven't found any way to accomplish this. I tried make a custom editor template (using columns.Bound(s => s.FieldId).EditorTemplateName("_TreeEditorTemplate")) that render the treeview, but the treeview is not an input and is not selectable. I also thinked in make an editor that use a kendo dropdownlist with the tree inside but this is no currently supported by kendo. Any ideas???
Have you looked at the sample on the Kendo site: https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Editing/use-treeview-as-grid-editor
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "//demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1 } },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
},
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
edit: function (e) {
//checking if a cell from the Test column is opened for editing
var dummyInput = e.container.find("input[name='test']");
if (dummyInput.length > 0) {
var treeView = $(e.container).find(".treeViewEditor").data("kendoTreeView");
var originalItem = treeView.findByText(dummyInput.val());
if (originalItem != null) {
// Select the item based on the field value
treeView.select(originalItem);
}
}
},
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{
field: "test", title: "Test", width: 120,
editor: function (container, options) {
var input = $("<input class='tveInput'/>");
input.attr("name", options.field);
var tvDiv = $("<div class='treeViewEditor'></div>");
$(tvDiv).kendoTreeView({
animation: false,
dataSource: [
{
text: "foo1"
},
{
text: "foo2",
items: [
{ text: "bar" },
{ text: "bar1" },
{ text: "bar2" }
]
}
]
});
var treeView = $(tvDiv).data("kendoTreeView");
$(tvDiv).find(".k-in").mousedown(function (e) {
var clickedNode = $(e.toElement).closest("[role=treeitem]");
var dataItem = treeView.dataItem(clickedNode);
var dummyInput = clickedNode.closest("[role=gridcell]").find("input[name='test']");
dummyInput.val(dataItem.text);
dummyInput.trigger("change");
});
tvDiv.appendTo(container);
input.appendTo(container);
}
},
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120 },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
</script>
</div>
<style>
.tveInput {
display: none;
}
</style>
I have implemented the JqGrid in my application. I have done the edit,delete, insert operations but I am failing in searching the records. I have bind the data from the sql server.
Here is my script
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery.extend(jQuery.jgrid.edit, {
closeAfterEdit: true,
closeAfterAdd: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata); ;
}
});
jQuery.extend(jQuery.jgrid.del, {
ajaxDelOptions: { contentType: "application/json" },
onclickSubmit: function (eparams) {
var retarr = {};
var sr = jQuery("#contactsList").getGridParam('selrow');
rowdata = jQuery("#contactsList").getRowData(sr);
retarr = { PID: rowdata.PID };
return retarr;
},
serializeDelData: function (data) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
});
$.extend($.jgrid.defaults,
{ datatype: 'json' }
);
jQuery.extend(jQuery.jgrid.search, {
});
$("#contactsList").jqGrid({
url: '/WebService.asmx/GetListOfPersons1',
datatype: 'json',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['PID', 'First Name', 'Last Name', 'Gender'],
colModel: [
{ name: 'PID', width: 60, align: "center", hidden: true, searchtype: "integer", editable: true },
{ name: 'FirstName', width: 180, sortable: true, hidden: false, editable: true },
{ name: 'LastName', width: 180, sortable: false, hidden: false, editable: true },
{ name: 'Gender', width: 180, sortable: false, hidden: false, editable: true, cellEdit: true, edittype: "select", formater: 'select', editrules: { required: true },
editoptions: { value: getAllSelectOptions() }
}],
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'PID',
sortorder: "asc",
pager: jQuery('#gridpager'),
viewrecords: true,
gridview: true,
height: '100%',
editurl: '/WebService.asmx/EditRow',
// searchurl: '/WebService.asmx/Searchrow',
caption: 'Person details'
}).jqGrid('navGrid', '#gridpager', { edit: true, add: true, del: true, search: true });
jQuery("#contactsList").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
// jQuery("#contactsList").setGridParam({ data: results.rows, localReader: reader }).trigger('reloadGrid');
jQuery("#contactsList").jqGrid('setGridParam', { url: "WebService.asmx/searchrow", page: 1 }).trigger("reloadGrid");
});
function getAllSelectOptions() {
var states = { 'male': 'M', 'female': 'F' };
return states;
}
</script>
Here I have given the reference for searching in my asmx file like WebService.asmx/searchrow when I click the find button in the popup the cursor is moving to the specified method in the url.
Here is my question how can I get the user entered search parameter name and value to that method to perform the search operation .
I have defined the searchrow method like following
[WebMethod]
public List<Person> searchrow(HttpContext context)
{
return null;
}
Please help me to out from this problem or any other alternative to do the search operation in JQGrid.
thanks
purna
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