Showing posts with label Chart. Show all posts
Showing posts with label Chart. Show all posts

Implement Chart using DotNet HighCharts in ASP.NET MVC

In this article, I am going to explain you how to implement chart using DotNet HighCharts in ASP.NET MVC. Here we will create chart using hard-coded value but in later articles I will explain draw chart from database. Below is step by step tutorial.

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Installing DotNet.HighCharts

Now the next step is DotNet.HighCharts. Go to TOOLS → Library Package Manager → Manage NuGet Packages for Solution.. and a new window will open. Type and search for DotNet.HighChart and click on Install button as shown below. Once installed successfully, you can check DotNet.HighChart in references folder.

Adding DotNet.HighCharts
Installing DotNet.HighCharts

You can also install by using Package Manager Console. Go to TOOLS → Library Package Manager → Package Manager Console → write Install-Package DotNet.HighCharts and press enter. This will install DotNet.HighCharts in application.

Adding Controller

Next step is to add Controller to application. Add a new empty Controller class named as HomeController. After adding controller, a new action method will be created. Replace all code with below code.

Draw or implement Pie Chart, Column Chart and Doughnut Chart using Google Chart API in ASP.NET MVC

In this article, I am going to explain you how to draw or implement Pie Chart, Column Chart and Doughnut Chart using Google Chart API in ASP.NET MVC. We will first Entity Framework to load data from database and after that we will use ADO.NET code. Below is the step by step tutorial.

Creating Database Table

First we need to create a database table and insert some dummy records. Below is table script to create table. Table ProductSales has 3 columns Id, Month and SalesCount. Here we are plotting number of product sales against each month.
create table ProductSales
(
Id int primary key identity,
[Month] varchar(20),
SalesCount int
)
go
insert into ProductSales values('Jan',85)
insert into ProductSales values('Feb',90)
insert into ProductSales values('Mar',30)
insert into ProductSales values('Apr',46)
insert into ProductSales values('May',65)
insert into ProductSales values('Jun',75)
insert into ProductSales values('Jul',85)
insert into ProductSales values('Aug',60)
insert into ProductSales values('Sep',55)
insert into ProductSales values('Oct',40)
insert into ProductSales values('Nov',60)
insert into ProductSales values('Dec',90)

Adding Controller and Controller Action Method

The next step is to add controller and action method. Add a new controller named as HomeController and inside controller add a new action method ChartFunction as shown below. Return type of ChartFunction() should be JsonResult and data should be in List.
Using Entity Framework
using ChartDemo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ChartDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // Using Entity Framework
        public JsonResult ChartFunction()
        {
            ArticlesEntitiesDB db = new ArticlesEntitiesDB();
            var data = db.ProductSales.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}
Here we are going to use ADO.NET code to get data from database. Output will be same in both the cases.
Using ADO.NET Code
using ChartDemo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ChartDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        
        // Using ADO.NET Code
        public JsonResult ChartFunction()
        {
            string query = "select [Month],SalesCount from ProductSales";
            string constring = @"data source=#####;initial catalog=Articles;
            persist security info=True;user id=#####;password=#####;";
            List<ProductDetails> chartData = new List<ProductDetails>();
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            ProductDetails pd = new ProductDetails();
                            pd.Month = dr["Month"].ToString();
                            pd.SalesCount = Convert.ToInt32(dr["SalesCount"]);
                            chartData.Add(pd);
                        }
                    }
                    con.Close();
                }
            }
            return Json(chartData, JsonRequestBehavior.AllowGet);
        }
        class ProductDetails
        {
            public string Month { get; set; }
            public Nullable<int> SalesCount { get; set; }
        }
    }
}
Adding View
Next step is to add view, right click on Index action method and add a new view without any model. Below is the code to draw chart using Google API.
First add two JavaScript reference files. First for jQuery support and second for google api reference.In options, you can specify the css and other properties highlighted in yellow. You can specify the different type of chart highlighted in green.
@{
    ViewBag.Title = "Draw Chart Using Google Chart API";
}

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        $.ajax({
            type: "POST",
            url: "/Home/ChartFunction",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var dt = new google.visualization.DataTable();
                dt.addColumn('string', 'Month');
                dt.addColumn('number', 'Sales Count');
                for (var i = 0; i < data.length; i++) {
                    dt.addRow([data[i].Month, data[i].SalesCount]);
                }
                var options = {
                    title: 'Product Sales Month Wise'
                };
                var chart = new google.visualization.ColumnChart($("#chart")[0]);
                chart.draw(dt, options);
            },
            failure: function (r) {
                alert(r.d);
            },
            error: function (r) {
                alert(r.d);
            }
        });
    }
</script>

<fieldset>
    <legend>Google Chart API IN ASP.NET MVC</legend>
    <div id="chart" style="height: 400px;width:900px;"></div>
</fieldset>
Below the output for column chart.
Draw Column Chart using Google Chart API in ASP.NET MVC

To draw pie chart change from ColumnChart to PieChart as shown below.
var chart = new google.visualization.PieChart($("#chart")[0]);
Draw Pie Chart using Google Chart API in ASP.NET MVC

To draw Doughnut chart, make chart type to PieChart and add pieHole: 0.5 as shown below
    var options = {
        title: 'Product Sales Month Wise',
        pieHole: 0.5
    };
    var chart = new google.visualization.PieChart($("#chart")[0]);
    chart.draw(dt, options);
Draw Doughnut Chart using Google Chart API in ASP.NET MVC

Draw Chart on Button click

Until now, we were drawing chart when view is loaded and now to draw chart on button click modify the view as shown below.
1) Add a button control as shown in green.
2) Attach Click event to this button using jQuery as shown in yellow.
3) Add "callback": drawChart as shown in blue.
Now when you will click on button then chart will be loaded.
<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
            google.load("visualization", "1", { packages: ["corechart"], "callback": drawChart });
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                $.ajax({
                    type: "POST",
                    url: "/Home/ChartFunction",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var dt = new google.visualization.DataTable();
                        dt.addColumn('string', 'Month');
                        dt.addColumn('number', 'Sales Count');
                        for (var i = 0; i < data.length; i++) {
                            dt.addRow([data[i].Month, data[i].SalesCount]);
                        }
                        var options = {
                            title: 'Product Sales Month Wise',
                            pieHole: 0.5
                        };
                        var chart = new google.visualization.PieChart($("#chart")[0]);
                        chart.draw(dt, options);
                    },
                    failure: function (r) {
                        alert(r.d);
                    },
                    error: function (r) {
                        alert(r.d);
                    }
                });
            }
        });
    });
</script>

<input type="button" id="btn" value="Draw Chart"/>

<fieldset>
    <legend>Google Chart API IN ASP.NET MVC</legend>
    <div id="chart" style="height: 400px;width:900px;"></div>
</fieldset>
To draw Pie Chart in 3D make is3D :'true' in options.
    var options = {
        title: 'Product Sales Month Wise',
        pieHole: 0.5,
        is3D: 'true'
    };
Pie Chart in 3d look

Draw (Implement) chart in ASP.NET MVC using chart class

In this article, I am going to explain you how to draw or implement chart in ASP.NET MVC using Chart Class (System.Web.Helpers) in C#. Below is the step by step tutorial.

Creating ASP.NET MVC 5 application

First of all create a new asp.net mvc 5 empty project. I am using visual studio 2013.
1) Open visual studio.
2) Go to File → New → Project.
3) Select Visual C# → Web → ASP.NET Web Application.
4) Give project name MVCChartDemo and click on OK as shown below.
Creating asp.net mvc 5 application
A new window will open as shown below. Select Empty Template, check on MVC and click on OK.
Selecting asp.net mvc 5 template

Adding Controller

Next step is to add controller. Add a new controller with name 'Home'. By default Index ActionResult will be generated. Add a new ActionResult method DrawChart as shown below.
Add namespace → System.Web.Helpers to support chart class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace MVCChartDemo.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DrawChart()
        {
            new Chart(width: 500, height: 350)
            .AddTitle("Mobile Product Chart")
            .AddSeries(chartType: "column",
               xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
               yValues: new[] { "50", "60", "80", "30" })
            .Write("png");
            return null;
        }
    }
}

Adding View

Next step is to add View. Right click on Index method and click on Add View. Set View name as Index, set Template as Empty(without model) and click on OK. Add below code to load DrawChart method.
<div style="margin-left:150px;">
    <table>
        <tr>
            <td><img src="@Url.Action("DrawChart")" alt="Draw Chart in ASP.NET MVC" /></td>
        </tr>
    </table>
</div>
Now run your application and you will see the below output as bar chart is generated.
Creating asp.net mvc 5 application
Now to draw Pie Chart set from chartType: "column" to chartType: "pie".
Draw pie chart in asp.net mvc

Applying Themes

Now we will apply various theme to make chart look nicer. To apply theme, change below line of code while creating chart object.
public ActionResult DrawChart()
{
    new Chart(width: 500, height: 350, theme:ChartTheme.Green) // change in-built theme here 
    .AddTitle("Mobile Product Chart")
    .AddSeries(chartType: "column",
       xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
       yValues: new[] { "50", "60", "80", "30" })
    .Write("png");
    return null;
}
You can see the below chart after applying theme.
Applying inbuilt theme in chart

Applying Custom Themes

Now we can apply custom theme to chart.
public ActionResult DrawChart()
{
    string Mytheme = @"<Chart BackColor=""#99ffdb"" ForeColor=""Blue"">
                         <ChartAreas>
                            <ChartArea Name=""Default"" BackColor=""#ffedcc""></ChartArea>
                         </ChartAreas>
                       </Chart>";
    new Chart(width: 500, height: 300, theme: Mytheme)
    .AddTitle("Mobile Product Chart")
    .AddSeries(chartType: "column",
      xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
      yValues: new[] { "50", "60", "80", "30" })
    .Write("png");
    return null;
}
Applying inbuilt custom theme in chart in mvc
You can customize your theme as per your requirement. Below is the another customize css theme.
public ActionResult DrawChart()
{
    string Mytheme = @"<Chart BackColor=""#D3DFF0"" BackGradientStyle=""TopBottom"" BackSecondaryColor=""White"" BorderColor=""26, 59, 105"" BorderlineDashStyle=""Solid"" BorderWidth=""2"" Palette=""None"" 
    PaletteCustomColors=""97,97,97; 209,98,96; 168,203,104; 142,116,178; 93,186,215; 255,155,83; 148,172,215; 217,148,147; 189,213,151; 173,158,196; 145,201,221; 255,180,138"">
      <ChartAreas>
          <ChartArea Name=""Default"" _Template_=""All"" BackColor=""64, 165, 191, 228"" BackGradientStyle=""TopBottom"" BackSecondaryColor=""White"" BorderColor=""64, 64, 64, 64"" BorderDashStyle=""Solid"" ShadowColor=""Transparent"" /> 
      </ChartAreas>
      <Legends>
          <Legend _Template_=""All"" BackColor=""Transparent"" Font=""Trebuchet MS, 8.25pt, style=Bold"" IsTextAutoFit=""False"" /> 
      </Legends>
      <BorderSkin SkinStyle=""Emboss"" /> 
    </Chart>";
    new Chart(width: 500, height: 300, theme: Mytheme)
    .AddTitle("Mobile Product Chart")
    .AddSeries(chartType: "column",
      xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
      yValues: new[] { "50", "60", "80", "30" })
    .Write("png");
    return null;
}
Below is the output.
Applying inbuilt custom theme 2 in chart in mvc
Below is the another way to return chart from controller to view.
public ActionResult DrawChart()
{
    var chart = new Chart(width: 500, height: 350)
           .AddTitle("Mobile Product List")
           .AddSeries(chartType: "column",
             xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
             yValues: new[] { "50", "60", "80", "30" })
           .GetBytes("png");
    return File(chart, "image/bytes");
}