No Data Shown On JQGrid - c#

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

Related

How to bind string in ChartJs in asp.net using C#?

I'm trying to bind object to ChartJS datasets data but it's not appearing and there's no error.
Below is my C# Code:
[WebMethod]
public static List<object> GetChartData()
{
List<object> chartData = new List<object>();
List<string> labels = new List<string>();
List<int> data = new List<int>();
labels.Add("Completed jobs");
data.Add(Convert.ToInt32(90));
labels.Add("Current running jobs");
data.Add(Convert.ToInt32(10));
chartData.Add(labels.ToArray());
chartData.Add(data.ToArray());
return chartData;
}
My Client side code:
function OnSuccess_(reponse) {
var aData = reponse.d;
window.ubdChart = new Chart(t, {
type: "pie",
data: {
datasets: [{
hoverBorderColor: "#ffffff",
data: aData, // Bind int values here
backgroundColor: ["rgba(0,123,255,0.9)", "rgba(0,123,255,0.5)"]
}],
labels: ["Completed jobs", "Current running jobs"] //Bind label values here
},
}
})
};
It's working after changing the code as below.
function OnSuccess_(reponse) {
var aData = reponse.d;
console.log(aData);
window.ubdChart = new Chart(t, {
type: "pie",
data: {
datasets: [{
hoverBorderColor: "#ffffff",
data: aData[1],
backgroundColor: ["rgba(0,123,255,0.9)", "rgba(0,123,255,0.5)"]
}],
labels: aData[0]
},
options: {
legend: {
position: "bottom",
labels: { padding: 25, boxWidth: 20 }
}, cutoutPercentage: 0, tooltips: { custom: !1, mode: "index", position: "nearest" }
}
})
};

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.

jQgrid Search option is not working as expected

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.

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