Google Charts with ASP.NET MVC5

How to use Google Chart in your ASP.net MVC Project.

I will explain 2 ways .

1- return data with ViewBag .

2- Using JSON .

Code with ViewBag .

C# Code :

 public ActionResult GetChart()        {                       var result =// here Your Data From SQLServer As List                       var datachart = new object[result.Count ];                     int j = 0;            foreach(var i in result)            {                              datachart[j] = new object[] { i.CategoryName.ToString(), i.Frequence };                j++;            }            string datastr = JsonConvert.SerializeObject(datachart, Formatting.None);            ViewBag.dataj =new HtmlString(datastr);                                                          return View();        }

 

HTML Code:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><script>    var data1 = '@ViewBag.dataj';    var datass = JSON.parse(data1);   </script><script type="text/javascript">      // Load the Visualization API and the corechart package.      google.charts.load('current', {'packages':['corechart']});      // Set a callback to run when the Google Visualization API is loaded.      google.charts.setOnLoadCallback(drawChart);      // Callback that creates and populates a data table,      // instantiates the pie chart, passes in the data and      // draws it.      function drawChart() {          // Create the data table.        var data = new google.visualization.DataTable();        data.addColumn('string', 'CategoryName');        data.addColumn('number', 'Frequence');        data.addRows(datass);        // Set chart options        var options = {'title':'Categories',                       'width':400,                       'height':300};        // Instantiate and draw our chart, passing in some options.        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));        chart.draw(data, options);      }</script><div id="chart_div"></div>

 

 

Second one , With Ajax :

   [WebMethod]        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]        public  JsonResult GetChartData()        {            var result = //Your Data From SQL Server as List             var chartData = new object[result.Count + 1];            chartData[0] = new object[]{                    "CategoryName",                    "Frequence"                };            int j = 0;            foreach (var i in result)            {                j++;                chartData[j] = new object[] { i.CategoryName.ToString(), i.Frequence };            }            // return chartData;            return Json(chartData,JsonRequestBehavior.AllowGet);        }

HTML Code :

<script src="~/scripts/jquery-3.1.1.js"></script> <%-- Here We need to write some js code for load google chart with database data --%><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><script>                var chartData; // globar variable for hold chart data              //  google.load("visualization", "1", { packages: ["corechart"] });                google.charts.load('current', { 'packages': ['corechart'] });                // Here We will fill chartData                $(document).ready(function () {                    $.ajax({                        url: "GetChartData",                        data: "",                        dataType: "json",                        type: "POST",                        contentType: "application/json; chartset=utf-8",                        success: function (data) {                                                       chartData = data;                        },                        error: function () {                            alert("Error loading data! Please try again.");                        }                    }).done(function () {                        // after complete loading data                        google.setOnLoadCallback(drawChart);                        drawChart();                    });                });                    function drawChart() {                    var data = google.visualization.arrayToDataTable(chartData);                    var options = {                        title: "Categories",                        pointSize: 5                    };                    var pieChart = new google.visualization.Bar(document.getElementById('chart_div'));                    pieChart.draw(data, options);                }</script><div id="chart_div" style="width:500px;height:400px">    <%-- Here Chart Will Load --%></div>

 

 

You can find more in my Youtube Channal .

https://youtu.be/F-iD2ADMG-k

 

code:

https://github.com/Alaeddinalhamoud/GoogleChart-MVC



Share

Comments