Chart Web Helper in ASP.NET MVC 3 Beta

Posted by: Malcolm Sheridan , on 10/28/2010, in Category ASP.NET MVC
Views: 70475
Abstract: The following article demonstrates how to use the chart helper that is part of the Microsoft Web Helpers library in ASP.NET MVC 3 Beta

Adding charts to your application has always been a non trivial exercise. Charts can be hard to implement, but thanks to the new Microsoft Web Helpers library, adding charts to your website is simple. This library can be downloaded through NuPack. NuPack is a free open source package manager that makes it easy for you to find, install, and use .NET libraries in your projects. This article will show you how to download the library and start using some of these new helpers.

Before moving on, you need to download ASP.NET MVC 3 Beta and NuPack. Click here to download and install them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. The new MVC 3 Beta dialog can be seen below.

MVC3BetaDialog

Choose Razor as the view engine and click OK.

The next step is to download the Microsoft Web Helpers library through NuPack. Right click the website and choose Add Package Reference.

Add Package Reference

The Add Package Reference dialog will open. Search for Microsoft in the search box in the top right corner. Upon completion you'll see microsoft-web-helpers option. Select that option and click Install.

microsoft-web-helpers

Click Close to return to the project. Check the references and you'll see that the library has been added to the project. The screenshot below displays the newly added reference.

NewReference

Let’s start coding. There are many ways to get the chart to work, and one way is to have an action method render the chart to the view. Here’s some sample code: 

public ActionResult GetRainfallChart()
        {
            var key = new Chart(width: 600, height: 400)
                .AddSeries(
                    chartType: "bar",
                    legend: "Rainfall",
                    xValue: new[] { "Jan", "Feb", "Mar", "Apr", "May" },
                    yValues: new[] { "20", "20", "40", "10", "10" })
                .Write();
           
            return null;
        }

 
First in the code above I’m creating a new Chart object called key. From there I’m using the AddSeries method to add things such as the chart type, x and y values and also the legend. Because the chart is rendered as an image, to use the action you need to add an HTML image to your page like this: 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Index</title>
</head>
<body>
      <h1>Test Chart</h1>
   <div>
            <img src="/Home/GetRainfallChart" />
    </div>
</body>

</html>

The chart is displayed on the page as follows.

mvc test chart

If you wanted to change the chart to a pie chart, just modify the chartType property: 

public ActionResult GetRainfallChart()
        {
            var key = new Chart(width: 600, height: 400)
                .AddSeries(
                    chartType: "pie",
                    legend: "Rainfall",
                    xValue: new[] { "Jan", "Feb", "Mar", "Apr", "May" },
                    yValues: new[] { "20", "20", "40", "10", "10" })
                .Write();
           
            return null;
        }

 

mvc pie chart

To pass a data source that isn’t hard coded, you can use the DataBindTable method. It accepts any value that returns an IEnumerable object.

public ActionResult GetMonths()
        {
            var d = new DateTimeFormatInfo();
            var key = new Chart(width: 600, height: 400)
                .AddSeries(chartType: "column")
                .DataBindTable(d.MonthNames)
                .Write(format: "gif");
            return null;
        }


mvc bar chart

There are six types of charts at this stage. There may be more in future releases. Here’s the list.

 

 

 

  • Area
  • Bar
  • Column
  • Line
  • Pie
  • Stock

To use any of these just modify the chartType property.

As you can see these helpers are new to the Microsoft.Web.Helpers library and can be used in ASP.NET MVC 3 Beta. This chart helper makes it easy to add charts to your website.

The entire source code of this article can be downloaded over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by SkillForge .NET Training on Monday, November 1, 2010 4:53 PM
Excellent overview. Pingback from SkillForge blog.
Comment posted by Shelly on Thursday, November 18, 2010 10:41 AM
hi,
the source code is 404.0 - Not Found
Comment posted by Carol on Thursday, November 18, 2010 11:56 PM
Shelly the link has been fixed thanks!
Comment posted by vicky on Tuesday, January 25, 2011 12:51 PM
Hi, thanks for the tip. this worked great when I was using ASP.NET development server from visual studio. But doesnt seem to work when hosted in a virtual directory on my local IIS. Anything needs to be changed?
Comment posted by vicky on Tuesday, January 25, 2011 12:58 PM
Hi, thanks for the tip. this worked great when I was using ASP.NET development server from visual studio. But doesnt seem to work when hosted in a virtual directory on my local IIS. Anything needs to be changed?
Comment posted by vicky on Tuesday, January 25, 2011 2:14 PM
Found the solution for my problem

<img src = <%= Url.Content("~/Home/GetRainfallChart") %>" alt="chart">
Comment posted by Mike on Tuesday, April 5, 2011 3:54 AM
Can you add a label to the bar with the number on?
Comment posted by Stephen Phan on Thursday, May 26, 2011 7:54 PM
Hi Malcolm,
I'm implementing charts like these:
1. http://mathworld.wolfram.com/images/eps-gif/DotPlot_1000.gif
2. http://www.ats.ucla.edu/stat/stata/modules/graph8/twoway/defaul3.gif
Can you help?

Thanks,
Stephen
Comment posted by Sergey Ivanchenkov on Tuesday, July 12, 2011 8:48 AM
Images which come from the same exact URL are cached in browser and do not get downloaded twice. This means that if you include your Action method in "SRC" attribute of the image, it will load only once. When you refresh the page or wish to load an image for another data set or criteria, it will not call your action but rather load previously loaded cached image. Therefore, this solution to MVC charting is deceptive and would not work in real life applications. Put a break point in your action method and try re-loading page with "F5" for the simplest example and you will not hit the break point the second time. Re-starting your VS test web server by running new debugger session clears previously cached images, but once you put it all under IIS, closing the browser on the client side does not clear images. Therefore next time you visit this page, your action method will not be called because browser finds images, downloaded from your URL in "SRC" attribute and uses cached images.
Comment posted by Iliya Osipov on Sunday, September 4, 2011 7:16 AM
2 Sergey Ivanchenkov:
you need change your URL every time when you want new image, like in code below
<img src="@Url.Action("HitrateChart", "Account", new { id = new Random().Next(1,9999)})" alt="HitrateChart" />
Comment posted by Vijay on Sunday, May 13, 2012 12:39 AM
Great tutorial. Thanks a Million :)
Comment posted by asdasdasdasd on Sunday, April 7, 2013 11:33 PM
asdasd

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel