ASP.NET MVC 3 provides various helper methods that are used for different purposes. Chart helper method is one them, which makes it very easy to create charts in ASP.NET MVC. In this article, I will show you how you can use Chart helper in ASP.NET MVC. I will also show you how to use the themes provided by ASP.NET MVC to style your charts.  Then I will show how to create a custom theme for making your chart background as transparent.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project as seen below:

Chart Helper in ASP.NET MVC

Choose Razor as the view engine and click OK.Chart Helper in ASP.NET MVC

Add a controller in your project and give name as HomeController as shown in the below figure:Chart Helper in ASP.NET MVC

After adding a Controller adds the code as shown below:

using System.Web.Mvc;
using System.Web.Helpers;

namespace ChartDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Chart()
        {
            new Chart(width: 400, height: 200, theme: ChartTheme.Green)
                 .AddSeries(
                      chartType: "column",
                   xValue: new[] { "Math", "English", "Computer", "Science" },
                     yValues: new[] { "80", "90", "78", "68" })
                   .Write("png");
            return null;
        }
    }
}


The chart is rendered as an image, to use the action you need to add an HTML

image to your page like this: 

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        <img src="@Url.Action("Chart")" alt="" />
    </div>
</body>
</html>

The chart is displayed on the page as follows:


Chart Helper in ASP.NET MVC


Now, let's add a custom theme which set the background color of your chart to

transparent and chart area background color to Aqua:


public ActionResult Chart()
{
    string myTheme =
           @"<Chart BackColor=""Transparent"" ForeColor=""Navy"">
                      <ChartAreas>
                             <ChartArea Name=""Default"" BackColor=""Aqua"" ></ChartArea>                        </ChartAreas>
             </Chart>";
            new Chart(width: 400, height: 200, theme: myTheme)
                 .AddSeries(
                      chartType: "column",
                   xValue: new[] { "Math", "English", "Computer", "Science" },
                     yValues: new[] { "80", "90", "78", "68" })
                   .Write("png");
            return null;
}

  Run this application again, you will see the following screen:


Chart Helper in ASP.NET MVC

Thanks for reading this article and I think this will help you a lot.

  Modified On Apr-14-2018 03:15:38 AM

Leave Comment