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" }
}
})
};
Related
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 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 can generate a Pie Chart Just like the picture by using the code below
<script>
var pieChartData = [
{ label: "Data 1", data: 16, color: "#62cb31", },
{ label: "Data 2", data: 6, color: "#A4E585", },
{ label: "Data 3", data: 22, color: "#368410", },
{ label: "Data 4", data: 32, color: "#8DE563", }
];
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
</script>
Now what I want to do is to generate the var data = [] dynamically from Controller. How to do this? Also the data is from the Database.
By Combining Pranav Patel and Ghanshyam Singh answers
I was able able to reach the desired output
Model
public class GenderPieChart_Model
{
public string GenderDesc { get; set; }
public int GenderID { get; set; }
}
Controller
public JsonResult Gender()
{
Dashboard_Layer data = new Dashboard_Layer();
var lst = data.Gender();
return Json(lst, JsonRequestBehavior.AllowGet);
}
Business Layer
public IEnumerable<GenderPieChart_Model> Gender()
{
List<GenderPieChart_Model> data = new List<GenderPieChart_Model>();
using (SqlConnection con = new SqlConnection(Connection.MyConn()))
{
SqlCommand com = new SqlCommand("dbo.sp_Project_DashBoard 4", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
GenderPieChart_Model value = new GenderPieChart_Model();
value.GenderDesc = Convert.ToString(reader.GetValue(0));
value.GenderID = Convert.ToInt32(reader.GetValue(1));
data.Add(value);
}
}
return data;
}
View
<div class="flot-chart-content" id="_ByGender" style="height: 150px"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "#Url.Action("Gender", "Dashboard")",
content: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data;
var pieChartData = [];
$.each(data, function (i,v) {
pieChartData.push({ label: v.GenderDesc, data: v.GenderID, color: "#62cb31", });
})
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByGender"), pieChartData, pieChartOptions);
}
})
});
</script>
you can call when your controller on ready event and after getting data (returned Json from your controller) can process further. You can try like below
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "<YOUR URL>",
data: "<YOUR PARAMETER IF NEEDED>",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ //data is your json returned from controller
var myData = JSON.parse(data);
//create your 'pieChartData' from object 'myData'
//pieChartData =
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
}
});
});
</script>
Its simple just return Json from your controller:
first create a model class for the properties
public class Chart
{
public string label{get;set;}
public string data{get;set;}
public string color{get;set;}
}
MVC action method:-
public JsonResult Chart()
{
List<Chart> chartList=new List();
// Code to fetch Data in List chartList
return Json(chartList,JsonRequestBehaviour.AllowGet);
}
Ajax Call:-
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "/Controller/Chart",
data: "<YOUR PARAMETER IF NEEDED>",
dataType: "json",
success: function(data){
$.each(data,function(i,index){
// Code to plot Chart here
});
}
});
});
</script>
net mvc4 c# razor project i want to implement dotnet highcharts.For that i have created a jsonresult function to get the data from datatable and a cshtml file to render the file.
Here my issue is that
1. i dont how to pass the data from json to view
2. how to display the result for x axis and series in highcharts.
Am beginner in asp.net mvc 4 and Highcharts..
cshtml
enter code here
<script type="text/javascript">
$(function () {
debugger;
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Audience Live Data'
},
subtitle: {
text: 'Mainadv'
},
xAxis: {
categories: [mySeries]
},
yAxis: {
min: 0,
title: {
text: 'Count'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Home',
data: [{ data: data }]
}, {
name: 'Category',
data: [{ data: data }]
}, {
name: 'Product',
data: [{ data: data }]
}, {
name: 'Basket',
data: [{ data: data }]
},{
name: 'Checkout',
data: [{ data: data }]
}]
});
});
</script>
Script file
<script type="text/javascript">
// the button action
debugger;
var url = "/AudienceLive/GetAudLiveChartData/";
$.ajax({
url: url,
cache: false,
Type: 'POST',
success: function (myData) {
var mySeries = [];
for (var i =0; i < myData.length; i++) {
mySeries.push([myData[i]]);
}
var chart = $('#container').highcharts();
chart.series[0].setData(mySeries);
// chart.series[0].pointStart=;
}, error: function (response) {
alert("error : " + response);
}
});
</script>
JsonResult Function
public JsonResult GetAudLiveChartData()
{
AudienceLiveRepo objlive=new AudienceLiveRepo ();
List<string> test=new List<string>();
DataTable dt = objlive.GetTable();
if(dt!=null)
{
if(dt.Rows.Count>0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
test.Add(Convert.ToString(dt.Rows[i][0]));
test.Add(Convert.ToString(dt.Rows[i][1]));
test.Add(Convert.ToString(dt.Rows[i][2]));
test.Add(Convert.ToString(dt.Rows[i][3]));
test.Add(Convert.ToString(dt.Rows[i][4]));
test.Add(Convert.ToString(dt.Rows[i][5]));
}
}
}
objlive = null;
return Json(test, JsonRequestBehavior.AllowGet);
}
View cshtml
$(document).ready(function () {
$.ajax({
url: "/home/ChartData",
type: 'POST',
dataType: 'json'
}).success(function (dataChart) {
var Xaxis = [];//skapa tre olika array
var dataseries = [];
for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var XcategoreisItem = items.id;
var seriesData = items;
Xaxis.push(XcategoreisItem);
dataseries.push(seriesData);
console.log(dataseries);
}
getchart(Xaxis, dataseries);
}).error(function (er, xhr, e) {
console.log("Error: ", er, xhr, e);
})
});
function getchart(Xaxis, dataseries) {
$('#container').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
title: {
text: 'Zooming and panning'
},
subtitle: {
text: 'Click and drag to zoom in. Hold down shift key to pan.'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}%',
}
}
},
xAxis: {
categories: Xaxis
},
yAxis: {
title: {
text: 'Y axis text'
},
series: [{
name: 'Id',
data: dataseries
}]
});
};
HomeController
public ActionResult ChartData()
{
TbChart db = new TbChart();
var TbChartData = db.getYaxis();
return this.Json(TbChartData, JsonRequestBehavior.AllowGet);
}
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