Generating Chart Dynamically In MVC Using Chart.js

In this article, we shall learn how to generate runtime chart in MVC using Chart.js.

Introduction

In this article, we shall learn how to generate charts like Bar chart, Line chart and Pie chart in an MVC web application dynamically using Chart.js which is an important JavaScript library for generating charts. Chart.js is a simple and flexible charting option which provides easy implementation to web developers and designers. We can generate almost every type of chart using chart.js. We shall implement it step by step for generating the chart, as shown below.
 
Let's get started now.
 
Create MVC Web Application
 
To create an MVC web application, first, open Visual Studio and click on File >> New project, as shown in the below image.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
It will open a new window as shown below. Here, you have to click on the web option. Now, give the name of the project and set the location of the project where you want to save the file.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Now, to select the project template, you have to click on the MVC template and I have used "No Authentication" as highlighted below.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Now, the application has already been created and all the files as per the MVC web template are also created in the application. It looks like below.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Adding Controller to the Application
 
To add a controller, right-click on the Controllers folder available in the Solution Explorer and select the "Add Controller" option.
 
Add >> Controller.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
The new next window will open where choose option: MVC 5 Controller - Empty and click on the "Add" button, as shown below.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Now finally, you have to give the name of the Controller and click on the "Add" button. I have given the name of the controller as ChartInMVCRuntimeController. Here, you do not have to remove the word Controller from the controller name as it is default.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Now, the Controller has been added and we can see it in the Controllers folder available in Solution Explorer.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Adding View to the Application
 
First, right-click on the Views folder and select the "Add New Folder" option as shown below. Here, give the name of the folder as RuntimeChart as I have given in my project.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Now, right-click on the newly created folder RuntimeChart and select the "Add View" option, as shown below.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Now, give the name of the View as below.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Now, the new View has been added which can be shown in Solution Explorer, as shown below.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Calling Action To Return View
 
Now, modify the Index action as shown below to return the view which will display on the browser. 
  1. public ActionResult Index()  
  2. {  
  3.          return View("~/Views/RuntimeChart/ChartInMVC.cshtml");  
  4. }  
Adding Table and TextBox to View
 
To add a simple HTML table and a textbox for entering the value, just copy the below HTML code and paste it to the new View which you have just added.
 
The below HTML code also contains three separate divs which have been used to generate the chart dynamically later.
  1. @{  
  2.     ViewBag.Title = "ChartInMVC";  
  3. }  
  4.   
  5. <style type="text/css">  
  6.     label {  
  7.         font-weight: normal;  
  8.         font-size: 11px;  
  9.         vertical-align: middle;  
  10.     }  
  11.   
  12.     body {  
  13.         color: black;  
  14.     }  
  15.   
  16.     textbox {  
  17.         font-weight: normal;  
  18.         font-size: 11px;  
  19.         vertical-align: middle;  
  20.         color: black;  
  21.     }  
  22.   
  23.     .form-control, select {  
  24.         font-weight: normal;  
  25.         font-size: 11px;  
  26.     }  
  27.   
  28.     .container {  
  29.         width: 80%;  
  30.         margin: 15px auto;  
  31.         color: black;  
  32.     }  
  33. </style>  
  34.   
  35. @using (Html.BeginForm("", "", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  36. {  
  37.     <div class="form-horizontal">  
  38.         <div class="row">  
  39.             <div class="col-md-12">  
  40.                 <div class="form-horizontal">  
  41.                     <div class="row">  
  42.                         <div class="col-md-12">  
  43.                             <div class="col-md-4">  
  44.                                 <div class="form-group">  
  45.                                     <div class="col-md-8">  
  46.                                         <label class="control-label">Enter Your Expenses Below</label>  
  47.                                     </div>  
  48.                                 </div>  
  49.                             </div>  
  50.   
  51.                         </div>  
  52.                     </div>  
  53.   
  54.                     <div class="row">  
  55.                         <div class="col-md-12">  
  56.                             <div class="col-md-12">  
  57.                                 <div class="form-group">  
  58.                                     <div class="col-md-12">  
  59.                                         <table class="table table-bordered table-responsive">  
  60.                                             <thead>  
  61.                                                 <tr>  
  62.                                                     <th scope="col">  
  63.                                                         <label class="control-label">Education</label>  
  64.                                                     </th>  
  65.                                                     <th scope="col">  
  66.                                                         <label class="control-label">Lodging</label>  
  67.                                                     </th>  
  68.                                                     <th scope="col">  
  69.                                                         <label class="control-label">Fooding</label>  
  70.                                                     </th>  
  71.                                                     <th scope="col">  
  72.                                                         <label class="control-label">Travelling</label>  
  73.                                                     </th>  
  74.                                                     <th scope="col">  
  75.                                                         <label class="control-label">Communication</label>  
  76.                                                     </th>  
  77.                                                     <th scope="col">  
  78.                                                         <label class="control-label">Others</label>  
  79.                                                     </th>  
  80.                                                 </tr>  
  81.                                             </thead>  
  82.                                             <tbody>  
  83.                                                 <tr>  
  84.                                                     <th scope="row">  
  85.                                                         <input type="text" class="form-control" id="txtEducation" />  
  86.                                                     </th>  
  87.                                                     <th scope="row">  
  88.                                                         <input type="text" class="form-control" id="txtLodging" />  
  89.                                                     </th>  
  90.                                                     <th scope="row">  
  91.                                                         <input type="text" class="form-control" id="txtFooding" />  
  92.                                                     </th>  
  93.                                                     <th scope="row">  
  94.                                                         <input type="text" class="form-control" id="txtTravelling" />  
  95.                                                     </th>  
  96.                                                     <th scope="row">  
  97.                                                         <input type="text" class="form-control" id="txtCommunication" />  
  98.                                                     </th>  
  99.                                                     <th scope="row">  
  100.                                                         <input type="text" class="form-control" id="txtOthers" />  
  101.                                                     </th>  
  102.                                                 </tr>  
  103.                                                 <tr>  
  104.                                                     <th scope="row" colspan="2">  
  105.                                                         <div id="chartContainerPie" class="containerPie">  
  106.                                                             <canvas id="myChart"> </canvas>  
  107.                                                         </div>  
  108.                                                     </th>  
  109.                                                     <th scope="row" colspan="2">  
  110.                                                         <div id="chartContainer" class="container">  
  111.                                                             <canvas id="myChartPie"> </canvas>  
  112.                                                         </div>  
  113.                                                     </th>  
  114.                                                     <th scope="row" colspan="2">  
  115.                                                         <div id="chartContainerLine" class="containerLine">  
  116.                                                             <canvas id="myChartLine"> </canvas>  
  117.                                                         </div>  
  118.                                                     </th>  
  119.                                                 </tr>  
  120.   
  121.                                             </tbody>  
  122.                                         </table>  
  123.                                     </div>  
  124.                                 </div>  
  125.                             </div>  
  126.                         </div>  
  127.                     </div>  
  128.                 </div>  
  129.             </div>  
  130.         </div>  
  131.     </div>  
  132.   
  133. }  

Now run the application and it will look like as below in the browser.

Generating Chart Dynamically In MVC Using Chart.js 
 
Adding Jquery Reference To View
 
Now, to add a jQuery reference to your View, just add the below code in the View. 
  1. <script src="~/Scripts/jquery-1.10.2.js"></script>  

Adding Chart.js Reference To View

To add the chart.js reference to the application, go to the site here and select the version of the chart.js from the dropdown as shown below. Now, include the link in your application in the script tag, as shown below. 
  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>  
Generating Chart Dynamically In MVC Using Chart.js 
 
Adding Action To Controller
 
Now we need to add another action for getting the result into JSON format which we will assign to the chart datasource. Here, we will return the result into a JSON string containing -
  1. [HttpPost]  
  2.        public JsonResult NewChart(string strEducation, string strLodging, string strFooding, string strTravelling, string strCommunication, string strOthers,  
  3.            decimal educationValue,decimal lodgingValue, decimal foodingValue, decimal travellingValue, decimal communicationValue, decimal othersValue)  
  4.        {  
  5.            educationValue = Math.Round(educationValue, 0);  
  6.            lodgingValue = Math.Round(lodgingValue, 0);  
  7.            foodingValue = Math.Round(foodingValue, 0);  
  8.            travellingValue = Math.Round(travellingValue, 0);  
  9.            communicationValue = Math.Round(communicationValue, 0);  
  10.   
  11.            List<object> iData = new List<object>();  
  12.            //Creating sample data    
  13.            DataTable dt = new DataTable();  
  14.            dt.Columns.Add("Expense", System.Type.GetType("System.String"));  
  15.            dt.Columns.Add("ExpenseValues", System.Type.GetType("System.Int32"));  
  16.   
  17.            //For Education  
  18.            DataRow dr = dt.NewRow();  
  19.            dr["Expense"] = strEducation;  
  20.            dr["ExpenseValues"] = educationValue;  
  21.            dt.Rows.Add(dr);  
  22.   
  23.            //For Lodging  
  24.            dr = dt.NewRow();  
  25.            dr["Expense"] = strLodging;  
  26.            dr["ExpenseValues"] = lodgingValue;  
  27.            dt.Rows.Add(dr);  
  28.   
  29.            //For Fooding  
  30.            dr = dt.NewRow();  
  31.            dr["Expense"] = strFooding;  
  32.            dr["ExpenseValues"] = foodingValue;  
  33.            dt.Rows.Add(dr);  
  34.   
  35.            //For Travelling  
  36.            dr = dt.NewRow();  
  37.            dr["Expense"] = strTravelling;  
  38.            dr["ExpenseValues"] = travellingValue;  
  39.            dt.Rows.Add(dr);  
  40.   
  41.            //For Communication  
  42.            dr = dt.NewRow();  
  43.            dr["Expense"] = strCommunication;  
  44.            dr["ExpenseValues"] = communicationValue;  
  45.            dt.Rows.Add(dr);  
  46.   
  47.            //For Others  
  48.            dr = dt.NewRow();  
  49.            dr["Expense"] = strCommunication;  
  50.            dr["ExpenseValues"] = othersValue;  
  51.            dt.Rows.Add(dr);  
  52.   
  53.            //Looping and extracting each DataColumn to List<Object>    
  54.            foreach (DataColumn dc in dt.Columns)  
  55.            {  
  56.                List<object> x = new List<object>();  
  57.                x = (from DataRow drr in dt.Rows select drr[dc.ColumnName]).ToList();  
  58.                iData.Add(x);  
  59.            }  
  60.            ViewBag.ChartData = iData;  
  61.            //Source data returned as JSON    
  62.            return Json(iData, JsonRequestBehavior.AllowGet);  
  63.        }  
Adding Function For Passing Data In Action And Generating Chart
 
Now, we need to add the below jQuery function which will pass data to the action and get the JSON value which we have assigned as a data source to the chart.
  1. <script type="text/javascript">  
  2.     function GenerateRuntimeGraph() {  
  3.         var educationValue = $('#txtEducation').val();  
  4.         var lodgingValue = $('#txtLodging').val();  
  5.         var foodingValue = $('#txtFooding').val();  
  6.         var travellingValue = $('#txtTravelling').val();  
  7.         var communicationValue = $('#txtCommunication').val();  
  8.         var othersValue = $('#txtOthers').val();  
  9.   
  10.         //setting default values  
  11.         if (educationValue == "") {  
  12.             educationValue = 0;  
  13.         }  
  14.         if (lodgingValue == "") {  
  15.             lodgingValue = 0;  
  16.         }  
  17.         if (foodingValue == "") {  
  18.             foodingValue = 0;  
  19.         }  
  20.         if (travellingValue == "") {  
  21.             travellingValue = 0;  
  22.         }  
  23.         if (communicationValue == "") {  
  24.             communicationValue = 0;  
  25.         }  
  26.         if (othersValue == "") {  
  27.             othersValue = 0;  
  28.         }  
  29.   
  30.         $.ajax({  
  31.             type: "POST",  
  32.             url: '@Url.Action("NewChart", "ChartInMVCRuntime")',  
  33.             data: JSON.stringify({  
  34.                 "strEducation""Education",  
  35.                 "strLodging""Lodging",  
  36.                 "strFooding""Fooding",  
  37.                 "strTravelling""Travelling",  
  38.                 "strCommunication""Communication",  
  39.                 "strOthers""Others",  
  40.                 educationValue: educationValue,  
  41.                 lodgingValue: lodgingValue,  
  42.                 foodingValue: foodingValue,  
  43.                 travellingValue: travellingValue,  
  44.                 communicationValue: communicationValue,  
  45.                 othersValue: othersValue  
  46.             }),  
  47.             contentType: "application/json",  
  48.             dataType: "json",  
  49.             success: function (chData) {  
  50.                 var aData = chData;  
  51.                 var aLabels = aData[0];  
  52.                 var aDatasets1 = aData[1];  
  53.   
  54.                 //For Bar Chart  
  55.                 var ctx = document.getElementById("myChart").getContext('2d');  
  56.                 ctx.height = 900;  
  57.                 var myChart = new Chart(ctx, {  
  58.                     type: 'bar',  
  59.                     height: "230px",  
  60.                     width: "300px",  
  61.                     autoSkip: false,  
  62.                     responsive: false,  
  63.                     animation: false,  
  64.                     showDatapoints: true,  
  65.                     legend: { position: 'bottom' },  
  66.                     data: {  
  67.                         //labels: ["M", "T", "W", "T", "F", "S", "S"],  
  68.                         labels: ["Education""Lodging""Fooding""Travelling""Communication""Others"],  
  69.                         datasets: [{  
  70.                             label: 'Monthly Expenses',  
  71.                             data: [educationValue, lodgingValue, foodingValue, travellingValue, communicationValue, othersValue],  
  72.                             backgroundColor: ["red""blue""green""yellow""pink""brown"]  
  73.                         }]  
  74.                     }, options: {  
  75.                         events: ['click'],  
  76.                         scaleShowValues: true,  
  77.                         scales: {  
  78.                             yAxes: [{  
  79.                                 ticks: {  
  80.                                     beginAtZero: true  
  81.                                 }  
  82.                             }],  
  83.                             xAxes: [{  
  84.                                 ticks: {  
  85.                                     autoSkip: false  
  86.                                 }  
  87.                             }]  
  88.                         }  
  89.                     }  
  90.                 });  
  91.   
  92.   
  93.                 //For Pie Chart  
  94.                 var ctx1 = document.getElementById("myChartPie").getContext('2d');  
  95.                 var myChart = new Chart(ctx1, {  
  96.                     type: 'pie',  
  97.                     height: "230px",  
  98.                     width: "300px",  
  99.                     responsive: false,  
  100.                     animation: false,  
  101.                     legend: { position: 'bottom' },  
  102.                     data: {  
  103.                         //labels: ["M", "T", "W", "T", "F", "S", "S"],  
  104.                         labels: ["Education""Lodging""Fooding""Travelling""Communication""Others"],  
  105.                         datasets: [{  
  106.                             label: 'Monthly Expenses',  
  107.                             data: [educationValue, lodgingValue, foodingValue, travellingValue, communicationValue, othersValue],  
  108.                             backgroundColor: ["red""blue""green""yellow""pink""brown"]  
  109.                         }]  
  110.                     }, options: {  
  111.                         // This chart will not respond to mousemove, etc  
  112.                         events: ['click']  
  113.                     }  
  114.                 });  
  115.   
  116.                 //For Line Chart  
  117.                 var ctx = document.getElementById("myChartLine").getContext('2d');  
  118.                 var myChart = new Chart(ctx, {  
  119.                     type: 'line',  
  120.                     height: "230px",  
  121.                     width: "300px",  
  122.                     responsive: false,  
  123.                     animation: false,  
  124.                     legend: { position: 'bottom' },  
  125.                     data: {  
  126.                         //labels: ["M", "T", "W", "T", "F", "S", "S"],  
  127.                         labels: ["Education""Lodging""Fooding""Travelling""Communication""Others"],  
  128.                         datasets: [{  
  129.                             label: 'Monthly Expenses',  
  130.                             data: [educationValue, lodgingValue, foodingValue, travellingValue, communicationValue, othersValue],  
  131.                             backgroundColor: "rgb(66, 134, 244)"  
  132.                         }]  
  133.                     }, options: {  
  134.                         events: ['click'],  
  135.                         scaleShowValues: true,  
  136.                         scales: {  
  137.                             yAxes: [{  
  138.                                 ticks: {  
  139.                                     beginAtZero: true  
  140.                                 }  
  141.                             }],  
  142.                             xAxes: [{  
  143.                                 ticks: {  
  144.                                     autoSkip: false  
  145.                                 }  
  146.                             }]  
  147.                         }  
  148.                     }  
  149.                 });  
  150.   
  151.   
  152.             },  
  153.             "error"function (data) {  
  154.                 alert("Some Error Occured!");  
  155.             }  
  156.         });  
  157.     }  

Adding Textbox Event

Now to add calling the action and passing textbox value to action we need to add the below events in jquery into the view. All the events are on the key press event of the textbox. 
  1. //Calling Above Function On Key Press Event  
  2.     $("#txtEducation").keyup(function () {  
  3.         GenerateRuntimeGraph();  
  4.     });  
  5.   
  6.     $("#txtLodging").keyup(function () {  
  7.         GenerateRuntimeGraph();  
  8.     });  
  9.   
  10.     $("#txtFooding").keyup(function () {  
  11.         GenerateRuntimeGraph();  
  12.     });  
  13.   
  14.     $("#txtTravelling").keyup(function () {  
  15.         GenerateRuntimeGraph();  
  16.     });  
  17.   
  18.     $("#txtCommunication").keyup(function () {  
  19.         GenerateRuntimeGraph();  
  20.     });  
  21.   
  22.     $("#txtOthers").keyup(function () {  
  23.         GenerateRuntimeGraph();  
  24.     });  
Run The Application
 
Now we have almost completed the steps needed. So, run the application and it will show in the browser as shown below. Here you need to enter the value of expenses and the chart will be generated instantly as shown below.
 
Generating Chart Dynamically In MVC Using Chart.js 
 
Summary

In this article, we have seen how to create an MVC web application and learned to generate a chart in MVC dynamically using chart.js and jquery. Apart from this, we have seen how to write jquery function and learned how to call a jquery function on the keypress event of the textbox. 

I hope you learned and enjoyed it. I look forward to seeing your feedback.