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" }
}
})
};
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,
});
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.
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.
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.