How to create charts with Asp.Net MVC 5 using ChartJs
- Pradeep Kumar
- Sep 12, 2020
- 3 min read
Updated: Sep 15, 2020
In this blog i will write how to get the json data adapted to the chart js json syntax
For more information on chart js json syntax click here
About chart js
Chart Js is an java script open source library.
It is lightweight & responsive.
Set up environment for chart js
Create an Asp.Net MVC web application.
Download the chart js library .
In Bundle.config file you have to bundle the chart js script file as below
bundles.Add(new ScriptBundle("~/bundles/chartjs").Include(
"~/Scripts/chatjs.bundle.js"));
In _Layout.cshtml file make sure all the scripts and styles are placed inside the head section.
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/chartjs")
@RenderSection("scripts", required: false)
</head>
Implementation of charts in Asp.net web MVC c# using chart js
create a chart controller as "ChartController.cs"
create model class file "GraphData.cs", "GraphDataSet.cs", "ScatterConfig.cs"
In GraphData.cs file add the below code
public class GraphData
{
[JsonProperty("datasets")]
public List<GraphDataSet> DataSets { get; set; }
}
In GraphDataSet.cs file add the below code
public class GraphDataSet
{
[JsonProperty("label")]
public string LabelForDataSet { get; set; }
[JsonProperty("data")]
public List<ScatterConfig> DataForDataSet { get; set; }
[JsonProperty("fill")]
public bool IsFilled { get; set; }
[JsonProperty("borderColor")]
public string BorderColorForDataSet { get; set; }
[JsonProperty("backgroundColor")]
public string BackgroundColorForDataSet { get; set; }
[JsonProperty("showLine")]
private bool IsLineShowed
{
get { return true; }
}
[JsonProperty("pointRadius")]
private double PointRadiusForDataSet
{
get { return 0; }
}
[JsonProperty("borderWidth")]
private double BorderWidthForDataSet
{
get { return 2; }
}
}
In ScatterConfig.cs file add the below code
public class ScatterConfig
{
[JsonProperty("x")]
public double X { get; set; }
[JsonProperty("y")]
public double Y { get; set; }
}
ChartController.cs file on creating generates Index action
Add View Index.cshtml for ChartController.cs Index action(get method)
In Index.cshtml file add the below code
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<h4>Chart rendered from asp.net mvc</h4>
<div style="width: 900px; height: 800px">
<canvas id="scatterChart"></canvas>
</div>
Create a script file canvasScript.js in scripts folder
In canvasScript.js file add the below code
/*** functions ***/
$(document).ready(function () {
GetChartData();
})
// ajax call to get chart data from back end
GetChartData = function () {
$.ajax({
url: '/Chart/GetGraphData',
//data: JSON.stringify(jsonObject),
type: "post",
dataType: "json",
contentType: "application/json",
success: function (respnse) {
var canvasElement = document.getElementById("scatterChart");
var ctx = canvasElement.getContext('2d');
BindChartDataToCanvasElement(respnse.data, ctx);
}
})
}
BindChartDataToCanvasElement = function (graphData, ctx) {
var graphData = JSON.parse(graphData);
console.log(graphData);
var myChart = new Chart(ctx, {
type: 'scatter',
height: "230px",
width: "300px",
responsive: false,
animation: false,
stacked: false,
legend: { position: 'bottom' },
data: graphData
, options: {
events: ['click'],
scaleShowValues: true,
scales: {
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'x axis label'
},
ticks: {
beginAtZero: true,
}
}],
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'y axis label'
},
ticks: {
beginAtZero: true,
min: 0,
//max: 1470,
//stepSize: 100
},
type: 'linear',
position: 'bottom'
}]
}
}
});
}
In Bundle.config file you have to replace the earlier bundle with the below code snippet or else server will exclude canvasScript.js file
bundles.Add(new ScriptBundle("~/bundles/chartjs").Include(
"~/Scripts/chatjs.bundle.js",
"~/Scripts/canvasScript.js"));
In ChartController.cs file add the post method to get graph data
[HttpPost]
public JsonResult GetGraphData()
{
GraphData graphData = new GraphData();
//do your calculations
List<GraphDataSet> graphDataSets = new List<GraphDataSet>()
{
new GraphDataSet()
{
LabelForDataSet = "1 yr",
DataForDataSet = GetData("1 yr"),
BorderColorForDataSet = "rgb(252, 3, 3)",
IsFilled = false,
},
new GraphDataSet()
{
LabelForDataSet = "2 yr",
DataForDataSet = GetData("2 yr"),
BorderColorForDataSet = "rgb(3, 252, 49)",
IsFilled = false,
},
new GraphDataSet()
{
LabelForDataSet = "5 yr",
DataForDataSet = GetData("5 yr"),
BorderColorForDataSet = "rgb(24, 3, 252)",
IsFilled = false,
},
new GraphDataSet()
{
LabelForDataSet = "10 yr",
DataForDataSet = GetData("10 yr"),
BorderColorForDataSet = "rgb(157, 3, 252)",
IsFilled = false,
},
new GraphDataSet()
{
LabelForDataSet = "25 yr",
DataForDataSet = GetData("25 yr"),
BorderColorForDataSet = "rgb(80, 150, 210)",
IsFilled = false,
},
};
graphData.DataSets = graphDataSets;
string jsonGraphdata = JsonConvert.SerializeObject(graphData);
return new JsonResult { Data = new { data = jsonGraphdata } };
}
public List<ScatterConfig> GetData(string key)
{
int min = 1;
int max = 1;
switch (key)
{
case "1 yr":
min = 1;
max = 100;
break;
case "2 yr":
min = 10;
max = 120;
break;
case "5 yr":
min = 20;
max = 100;
break;
case "10 yr":
min = 20;
max = 140;
break;
case "25 yr":
min = 30;
max = 140;
break;
}
List<ScatterConfig> data = new List<ScatterConfig>();
data.Add(new ScatterConfig()
{
X = 0.0,
Y = 0.0,
});
for (int i=0; i < 10; ++i)
{
Random r = new Random();
int x = r.Next(min + i, max/2);
int y = r.Next(max/2 + i, max);
data.Add(new ScatterConfig()
{
X = (double)x,
Y = (double)y,
});
}
data.Add(new ScatterConfig()
{
X = 50.0,
Y = 0.0,
});
return data;
}
Now lets run the application, Here is the screen shot of the output.

Thanks & Regards,
PRADEEP KUMAR BAISETTI
Associate Trainee – Enterprise Application Development
Digital Transformation
Comentários