HTML 5 Canvas chart in Asp.Net MVC

Implementing and displaying animated HTML 5 canvas charts from database using jQuery AJAX in ASP.Net MVC Razor is explained in the article below. The Canvas chart is implemented using Chart.js library and data is retrieved from the database.

Execute below script in database.

CREATE TABLE [dbo].[CountryDetails](
  [ID] [int] IDENTITY(1,1) NOT NULL,
  [Name] [nvarchar](50) NOT NULL,
  [Value] [int] NOT NULL,
  [City] [nvarchar](50) NULL,
 CONSTRAINT [PK_CountryDetails] PRIMARY KEY CLUSTERED 
(
  [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET IDENTITY_INSERT [dbo].[CountryDetails] ON 

GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (1, N'India', 35, N'Erode')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (2, N'China', 10, N'Chennai')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (3, N'Australia', 15, N'Chennai')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (4, N'Spain', 25, N'Chennai')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (5, N'Germany', 5, N'Chennai')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (6, N'Butan', 10, N'Chennai')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (7, N'India', 10, N'Chennai')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (8, N'China', 5, N'Erode')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (9, N'India', 5, N'Salem')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (10, N'India', 15, N'Ooty')
GO
INSERT [dbo].[CountryDetails] ([ID], [Name], [Value], [City]) VALUES (11, N'India', 5, N'Madurai')
GO
SET IDENTITY_INSERT [dbo].[CountryDetails] OFF
GO

In order to connect to back end add connection string for database connection in web.config file.

<connectionStrings>
    <add name="Constring" connectionString="Data Source=server;Initial Catalog=db;User ID=xx;Password=xxxxxx" providerName="System.Data.SqlClient"/>
  </connectionStrings>

 Controller

public ActionResult AjaxMethod()
       {
           return View();
       }

       [HttpPost]
       public ContentResult AjaxMethod(string country)
       {
           string query = "SELECT City,COUNT(ID) FROM CountryDetails WHERE Name = @Country Group by City";
           string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
           StringBuilder sb = new StringBuilder();
           using (SqlConnection con = new SqlConnection(constr))
           {
               using (SqlCommand cmd = new SqlCommand(query))
               {
                   cmd.CommandType = CommandType.Text;
                   cmd.Connection = con;
                   cmd.Parameters.AddWithValue("@Country", country);
                   con.Open();
                   using (SqlDataReader sdr = cmd.ExecuteReader())
                   {
                       sb.Append("[");
                       if (sdr.HasRows)
                       {
                           while (sdr.Read())
                           {
                               sb.Append("{");
                               System.Threading.Thread.Sleep(50);
                               string color = String.Format("#{0:X6}", new Random().Next(0x1000000));
                               sb.Append(string.Format("text :'{0}', value:{1}, color: '{2}'", sdr[0], sdr[1], color));
                               sb.Append("},");
                           }
                       }
                       sb = sb.Remove(sb.Length - 1, 1);
                       sb.Append("]");
                   }

                   con.Close();
               }
           }

           return Content(sb.ToString());
       }

View

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <h2>HTML5 Canvas charts in Asp.Net MVC</h2>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Country:
                <select id="ddlCountries">
                    <option value="India">India</option>
                    <option value="China">China</option>
                </select>
                <table id ="rblChartType" border="0">
                    <tr>
                        <td><input type="radio" name="ChartType" value="1" checked="checked"/>Pie</td>
                        <td><input type="radio" name="ChartType" value="2"/>Doughnut</td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>
                <div id="dvChart">
                </div>
            </td>
            <td>
                <div id="dvLegend">
                </div>
            </td>
        </tr>
    </table>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
    <script src="//cdn.jsdelivr.net/chart.js/0.2/Chart.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            LoadChart();
            $("#ddlCountries").bind("change", function () {
                LoadChart();
            });
            $("#rblChartType input").bind("click", function () {
                LoadChart();
            });
        });
        function LoadChart() {
            var chartType = parseInt($("#rblChartType input:checked").val());
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: "{country: '" + $("#ddlCountries").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function (response) {
                    $("#dvChart").html("");
                    $("#dvLegend").html("");
                    var data = eval(response);
                    var el = document.createElement('canvas');
                    $("#dvChart")[0].appendChild(el);
 
                    //Fix for IE 8
                    if ($.browser.msie && $.browser.version == "8.0") {
                        G_vmlCanvasManager.initElement(el);
                    }
                    var ctx = el.getContext('2d');
                    var userStrengthsChart;
                    switch (chartType) {
                        case 1:
                            userStrengthsChart = new Chart(ctx).Pie(data);
                            break;
                        case 2:
                            userStrengthsChart = new Chart(ctx).Doughnut(data);
                            break;
                    }
                    for (var i = 0; i < data.length; i++) {
                        var div = $("<div />");
                        div.css("margin-bottom", "10px");
                        div.html("<span style = 'display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
                        $("#dvLegend").append(div);
                    }
                },
                failure: function (response) {
                    alert('There was an error.');
                }
            });
       }
    </script>
</body>
</html>

Output