ASP.NET MVC: Bar Chart from JSON Data ViewBag - c#

I have a JSON data from database like below to build a dashboard in dashboard ASP.NET MVC. I would like to draw a daily and monthly bar chart with x-axis as datetime (Day) and y-axis as count of activities in a day.
JSON Data:
[{"count":42,"datetime":"2020-07-18T00:00:00"},{"count":49,"datetime":"2020-07-16T00:00:00"},{"count":90,"datetime":"2020-07-14T00:00:00"},{"count":85,"datetime":"2020-07-17T00:00:00"},{"count":100,"datetime":"2020-07-13T00:00:00"},{"count":38,"datetime":"2020-07-19T00:00:00"},{"count":53,"datetime":"2020-07-15T00:00:00"}]
and i want something like this
I've tried the following javascript code but can't. JSON data obtained from ViewBag.dataItems
<script type="text/javascript" >
window.onload = function () {
var result = #Html.Raw(ViewBag.dataItems);
var DataItem =[];
for (var i = 0; i < result.length; i++){
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
data: [{
type: "column",
DataItem: DataItem
}]
});
chart.render();
};
</script>
ThankYou

As I referred to some samples from https://canvasjs.com/docs/charts/chart-types/html5-column-chart/, they used dataPoints property instead of DataItem.
Here is a sample following your data. Hope to help, my friend :))
1. Controllers
public ActionResult Add()
{
ViewData["data"] = #"[{'count':42,'datetime':'2020-07-18T00:00:00'},{'count':49,'datetime':'2020-07-16T00:00:00'},{'count':90,'datetime':'2020-07-14T00:00:00'},{'count':85,'datetime':'2020-07-17T00:00:00'},{'count':100,'datetime':'2020-07-13T00:00:00'},{'count':38,'datetime':'2020-07-19T00:00:00'},{'count':53,'datetime':'2020-07-15T00:00:00'}]";
return View();
}
2. Views
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var result = #Html.Raw(ViewData["data"]);
this.console.log(result);
var DataItem = [];
for (var i = 0; i < result.length; i++) {
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Date Time Formatting"
},
data: [{
type: "column",
dataPoints: DataItem
}]
});
chart.render();
}
</script>

Related

Display bar graphs using ASP.NET MVC

I wrote a code to show data from DB in a table view. How can I show same data in Bar graph instead?
This my action method (Updated):
public ActionResult DataFromDataBase()
{
var mostRecentMonday = DateTime.Now.AddDays(-7).StartOfWeek(DayOfWeek.Monday);
var weekEnd = mostRecentMonday.AddDays(7).AddSeconds(-1); //will return the end of the day on Sunday
ViewBag.Monday = mostRecentMonday;
ViewBag.lastWeekSunday = weekEnd;
try
{
Formatting _jsonSetting = default;
ViewBag.DataPoints = JsonConvert.SerializeObject(db.Chats.Where(x => System.Data.Entity.DbFunctions.TruncateTime(x.MSTChatCreatedDateTime) >= mostRecentMonday
&& System.Data.Entity.DbFunctions.TruncateTime(x.MSTChatCreatedDateTime) <= weekEnd).GroupBy(a => System.Data.Entity.DbFunctions.TruncateTime(a.MSTChatCreatedDateTime)).Select(b => new ReportVM()
{
CreatdDate = b.Key,
ChatCountCreatdDate = b.Count()
}).ToList(), _jsonSetting);
return View();
}
catch (System.Data.Entity.Core.EntityException)
{
return View("Error");
}
catch (System.Data.SqlClient.SqlException)
{
return View("Error");
}
}
View to display Graphs
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer"></div>
<script type="text/javascript">
var result = #Html.Raw(ViewBag.DataPoints);
var dataPoints =[];
for(var i = 0; i < result.length; i++){
dataPoints.push({label:result[i].x, y:result[i].y});
}
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
zoomEnabled: true,
animationEnabled: true,
title: {
text: "Line Chart with Data-Points from DataBase"
},
data: [
{
type: "column",
dataPoints: dataPoints,
}
]
});
chart.render();
});
</script>
No successs. Used js library to display Graphs, but nothing is working for me. Can some one please help?
Go through below link to explore bar chart on chartjs, its free and easy to use charts,
you just have to specify proper data objects
Check below Example
https://www.chartjs.org/docs/latest/charts/bar.html

How to send Json Data from controller to javascript without in ASP.NET Core?

I am creating an application in that I need to create Treeview for that I take reference of this site
Actually this project is created in MVC Framework and currently, I am using ASP.NET CORE(v3.0) and when I try to send JSON using JavaScriptSerializer than it shows me an error that's why I am using Newtownsoft Json for convert List class to JSON.
Create.CSHTML
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div id="jstree">
</div>
<input type="hidden" name="selectedItems" id="selectedItems" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script type="text/javascript">
$(function () {
$('#jstree').on('changed.jstree', function (e, data) {
var i, j;
var selectedItems = [];
for (i = 0, j = data.selected.length; i < j; i++) {
//Fetch the Id.
var id = data.selected[i];
//Remove the ParentId.
if (id.indexOf('-') != -1) {
id = id.split("-")[1];
}
//Add the Node to the JSON Array.
selectedItems.push({
text: data.instance.get_node(data.selected[i]).text,
id: id,
parent: data.node.parents[0]
});
}
//Serialize the JSON Array and save in HiddenField.
$('#selectedItems').val(JSON.stringify(selectedItems));
}).jstree({
"core": {
"themes": {
"variant": "large"
},
"data": #ViewBag.Data
},
"checkbox": {
"keep_selected_style": false
},
"plugins": ["wholerow", "checkbox"],
});
});
</script>
MyContoller.cs
public ActionResult Create()
{
//Loop and add the Parent Nodes.
List<Menu> ParentMenus = _context.Menu.Where(t => t.ParentID == null).ToList();
foreach (Menu type in ParentMenus)
MenuBinding.Add(new TreeViewNode { id = type.MenuID.ToString(), parent = "#", text = type.Title });
List<Menu> ChildMenus = _context.Menu.Where(t => t.ParentID != null).ToList();
//Loop and add the Child Nodes.
foreach (Menu subType in ChildMenus)
{
MenuBinding.Add(new TreeViewNode { id = subType.MenuID.ToString(), parent = subType.ParentID.ToString(), text = subType.Title });
}
//Serialize to JSON string.
//ViewBag.Json = (new JavaScriptSerializer()).Serialize(nodes);
string JsonData = JsonConvert.SerializeObject(MenuBinding);
ViewBag.Data = JsonData;
return View();
}
In js side when I get data it is in an escape sequence when I try to unescape and than try to send that data then also this gives me an error.
Actual JSON:
[
{
"id":"2",
"parent":"#",
"text":"A"
},
{
"id":"5",
"parent":"#",
"text":"B"
},
{
"id":"3",
"parent":"2",
"text":"C"
},
{
"id":"4",
"parent":"2",
"text":"D"
}
]
Get JSON in javascript:
[
{
"id":"2",
"parent":"#",
"text":"A"
},
{
"id":"5",
"parent":"#",
"text":"B"
},
{
"id":"3",
"parent":"2",
"text":"C"
},
{
"id":"4",
"parent":"2",
"text":"D"
}
]
Can anyone please look into this and suggest me what should I have to change in my code?
There is little mistake in script.
<script type="text/javascript">
$(function () {
$('#jstree').on('changed.jstree', function (e, data) {
var i, j;
var selectedItems = [];
for (i = 0, j = data.selected.length; i < j; i++) {
//Fetch the Id.
var id = data.selected[i];
//Remove the ParentId.
if (id.indexOf('-') != -1) {
id = id.split("-")[1];
}
//Add the Node to the JSON Array.
selectedItems.push({
text: data.instance.get_node(data.selected[i]).text,
id: id,
parent: data.node.parents[0]
});
}
//Serialize the JSON Array and save in HiddenField.
$('#selectedItems').val(JSON.stringify(selectedItems));
}).jstree({
"core": {
"themes": {
"variant": "large"
},
"data": #Html.Raw(ViewBag.Data)//Here need to add Html.Raw instead of ViewBag.Data
},
"checkbox": {
"keep_selected_style": false
},
"plugins": ["wholerow", "checkbox"],
});
});
</script>

DataTables warning - Requested unknown parameter '0' for row 0, column 0

I am working with DataTable.js and trying to implement into MVC. I've written code as per below:
View:
<div id="container">
<div id="demo">
<h2>Index</h2>
<table id="myDataTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Event Name</th>
<th>Event Type</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
#section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "#Url.Action("AjaxHandler","DataTable")",
"bProcessing": true,
"aoColumns": [
{ "sName": "EventID" },
{ "sName": "EventName" },
{ "sName": "EventTypeTitle" }
]
});
});
</script>
}
And Controller:
public ActionResult Index()
{
return View();
}
public ActionResult AjaxHandler(jQueryDataTableParamModel param)
{
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = getAllEvent().Count(),
iTotalDisplayRecords = getAllEvent().Count(),
aaData = getAllEvent()
}, JsonRequestBehavior.AllowGet);
}
private List<EventModel> getAllEvent()
{
List<EventModel> model = new List<EventModel>();
EventModel model1 = new EventModel { EventID = 1, EventName = "Event 1", EventType = 1, EventTypeTitle = "General" };
model1.EventScheduleList = new List<EventScheduleModel> { new EventScheduleModel {EventScheduleID = 1 }, new EventScheduleModel { EventScheduleID = 2 } };
model.Add(model1);
return model;
}
I am getting DataTables warning: table id=myDataTable - Requested
unknown parameter '0' for row 0, column 0. For more information about
this error, please see http://datatables.net/tn/4
As I research about the error I could find that this particular error is occur when data is not in correct manner. but, when I check response, I am getting correct data.
Is it because I have returned more numbers of columns which are used
in View? or Do I send integer value in JSON?
I've attached fiddle link as well:
https://dotnetfiddle.net/MEoqg8
You need to make very small change in you JacaScript code which goes like this, which means instead of using sName you need to use data inside aoColumns array.
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": '#Url.Action("AjaxHandler","Home")',
"bProcessing": true,
"aoColumns": [
{
"data": "EventID",
"bSearchable": false,
"fnRender": function (oObj) {
return '<a href=\"Details/' +
oObj.aData[0] + '\">View</a>';
}
},
{ "data": "EventName" },
{ "data": "EventTypeTitle" }
]
});
});
</script>
You can check a fork from your fiddle here : https://dotnetfiddle.net/7sXghO

Live HighChart not displaying data

I am trying the code of highstocks which is given below
<script type="text/javascript">
$(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
// Create the chart
$('#container').highcharts('StockChart', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = <%=chartData%>
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title: {
text: 'Sensor Data'
},
exporting: {
enabled: false
},
series: [{
name: 'Sensor Value',
data: (function () {
//generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for (i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
<%= chartData%>
]);
}
return data;
})()
}]
});
});
</script>
and displaying it in to the container
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto; width: 733px;"></div>
The code behind is
public string chartData
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
GetData();
List<int> _data = new List<int>();
foreach (DataRow row in dt.Rows)
{
_data.Add((int)row["Id"]);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data); //this make your list in jSON format like [88,99,10]
Response.Write(chartData);
}
private void GetData()
{
StringBuilder str = new StringBuilder();
SqlConnection con = new SqlConnection("Data Source=INBDQ2WK2LBCD2S\\SQLEXPRESS;Initial Catalog=MCAS;Integrated Security=SSPI");
SqlDataAdapter adp = new SqlDataAdapter("select top 1 Id from Monitoring order by Id desc ", con);
adp.Fill(dt);
}
Here I have created a JSON and I am transferring it to the javascript for highchart.
The problem I am having is that it is showing only one point. The values which are also updated in the database it is not updating in the chart.
What is wrong with it?
In your code I can see this:
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = <%=chartData%>;
series.addPoint([x, y], true, true);
}, 1000);
I guess, that chartData variable is where you have stored new point? At least you expect to have there. However your variable chartData is assigned in HTML once, after page is loaded from server. That you will update value on server, doesn't mean value get updated on client side.
I advice to use AJAX calls, for example: http://www.highcharts.com/studies/live-server.htm (see sources for code example).

how to import JSON data into VS2012 to plot highcharts

I want to import the data from JSON file into my VS2012 c# code so that I can plot my highcharts based on the data in JSON file.
I have checked many video on youtube and file docs but couldnt locate single code that runs and give an output as required.
Do give me a sample code that will map a data from JSON file, use it in vs2012 and plot the highcharts.
----------------Updated Question-------------
Below is the function I am trying to call in java-script where I want to evoke data from JSON format, but I am not able to call my function, below is my code
<script>
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
alert("outside");
$.getJSON('data.json', function (data) {
alert("INside");
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
and want to pass the data to the highcharts ,Since I am novice, any help will be greatly appreciated.
==============EDIT 2 =====================================
the Json file am trying to use for the data is in following format.
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]
Thank You.
If JSON file is not rendering on the browser and your are getting 404 error then you might be facing the mime type handling problem, please refer the below link which resolves the issue,
getJSON method does not work
ASP.NET MVC Server Code:
namespace ABPMVCTest.Web.Controllers
{
[AbpMvcAuthorize]
public class HomeController : ABPMVCTestControllerBase
{
static Random _ran=new Random();
public ActionResult Index()
{
return View();
}
public ContentResult GetJsonResult()
{
var dataList = new List<ChartDataFormat>();
GetData(dataList, "总收入");
GetData(dataList, "投币收入");
GetData(dataList, "扫码充电收入");
GetData(dataList, "售线收入");
var dataJsonStr=JsonConvert.SerializeObject(dataList,new JsonSerializerSettings(){ContractResolver = new CamelCasePropertyNamesContractResolver()});
return Content(dataJsonStr);
}
private static List<ChartDataFormat> GetData(List<ChartDataFormat> dataList, string key)
{
var list = new List<int>();
for (int i = 0; i < 7; i++)
{
list.Add(_ran.Next(1, 3000));
}
dataList.Add(new ChartDataFormat
{
Name = key,
Data = list
});
return dataList;
}
}
class ChartDataFormat
{
public string Name { get; set; }
public List<int> Data { get; set; }
}
}
Client javascript Code:
$(function() {
Highcharts.setOptions({
lang: {
printChart: '打印图表',
downloadJPEG: '下载为JPEG图片',
downloadPDF: '下载为PDF',
downloadPNG: '下载为PNG图片',
downloadSVG: '下载为SVG矢量图',
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
weekdays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
}
});
var nowDate = new Date();
var option = {
chart: {
type: 'area'
},
title: {
text: '收入趋势图'
},
subtitle: {
text: '没有选择时间范围的话,默认显示当日/月前后3天/月的数据'
},
credits: {
enabled:false
},
xAxis: {
type: 'datetime',
tickmarkPlacement: 'on',
title: {
enabled: false
},
dateTimeLabelFormats: {
day: "%Y-%m-%d",
week: "%A",
month: "%Y-%m",
year: "%Y"
}
},
yAxis: {
title: {
text: '单位:元'
},
labels: {
formatter: function() {
return this.value;
}
}
},
tooltip: {
shared: true,
valueSuffix: ' 元',
dateTimeLabelFormats: {
day: "%Y-%m-%d,%A",
week: "%A开始, %Y-%m-%d",
month: "%Y-%m",
year: "%Y"
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
},
series: {
pointStart:Date.UTC(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate()-3) ,
pointInterval: 24 * 36e5 //一天
}
},
series: [{}]
}
var url = "/Home/GetJsonResult";
$.getJSON(url, function(data) {
option.series = data;
$('#container').highcharts(option);
});
});

Categories

Resources