Dynamic Charts In ASP.NET MVC RAZOR - Chart Helper AND Linq

Feb 18, 2019 BY xtreme


You can easily create Charts from database using Charts Helper class in ASP.NET MVC Razor. System.Web.Helpers namespace supports a rich set of chart options and methods including bar, line, pie, doughnut, funnel, area and more..

You can easily install System.Web.Helpers Assembly using Package Manger Console. Microsoft has moved this library to a Nuget package called “microsoft-web-helpers“. Installing that package seems to be equivalent to having the assembly.

PM> Install-Package microsoft-web-helpers


  • .NET Framework 4.5 +
  • ASP.NET MVC 4.0
  • System.Web.Helpers Package



        <td style="border-bottom:1px solid gray;padding:10px">            
            <img src="@Url.Action("_CreatePie")" alt="Pie Chart using MVC" />
Note: This calls Action Result in Dashboard Controller:


public ActionResult _CreatePie()
    int currentMonth = DateTime.Now.Month;
    int currentYear = DateTime.Now.Year;
    string PieHead = "This Month Saless";

    string[] status = null;
    string[] statuscounts = null;
    var leads = (from l in _leadRepository.Table
                where (l.created_at.Value.Month == currentMonth 
                && l.created_at.Value.Year == currentYear
                && l.created_by == UserId)
                group 1 by new
                into g
                select new
                    Status = g.Key,
                    Month = g.Key.status,
                    CountStatus = g.Count()

        status = leads.Select(l => l.Status.ToString()).ToArray();
        statuscounts = leads.Select(l => l.CountStatus.ToString()).ToArray();
    //Create pie chart
    var chart = new System.Web.Helpers.Chart(width: 600, height: 400)
    .AddSeries(chartType: "pie",
                    xValue: statusCodes,
                    yValues: statusCodeCounts)
    return File(chart, "image/bytes");

The System.Web.Helpers.Chart class has various methods to Add Legends, Add Title, X Axis Heading, Y Axis Heading, etc. Class also has properties to control width, height and so on.

Creating Title
X/Y Axis Title     
Add Legends
Add Width n Height
    var chart = new System.Web.Helpers.Chart(width: 600, height: 400)

The methods used in Chart Helper are:

  • Addtitle: This method adds the tile to the chart.
  • Addseries: It is used for providing data points and series of attributes for the chart.
  • SetXAxis: It sets the value for the horizontal axis (X-Axis).
  • SetYAxis: It sets the value for the vertical axis (Y-Axis).
  • Save: By using this method, we can save the chart image to the specified file.
  • SaveToCache: It saves the chart image in the system cache.