ASP.NET MVC 3 Beta: Built-in support for charts

ASP.NET MVC does not have built-in support for chart control and that’s why I worked out my own solution to make ASP.NET MVC support chart control. With ASP.NET MVC 3 we will get official support for charts right out of the box. In this posting I will show you how to use charts in ASP.NET MVC 3 Beta.

ASP.NET MVC 3 has cool support for charts. We have to create charts in our code or define them using XML. We have nice Chart class that offers us pretty cool fluent interface that is convenient to use. But let’s get started.

Page with chart

As a first thing we need a view where we show chart. Our view is simple and it contains only one image that is loaded from request made to controller.

@{
    View.Title =
"Home Page"
;
}
 

<h2>@View.Message</h2
>
<
p>
    <img src="/Home/Chart" 
/>
</
p
>

This page is index view of home controller. I just removed the welcome message and added img tag.

Displaying chart

Chart image is returned by controller action Chart(). In this action we will ask data from model and give it to view. We are using view here because I want to illustrate you something you should know.

public ActionResult Chart()
{
   
var model = new ChartModel
();
   
var
data = model.GetChartData();

   
return View(data);
}

Here is my primitive chart model.

public class ChartModel
{
   
public IList
GetChartData()
    {
       
return new ArrayList
        {
            
new
{ X = DateTime.Now.AddMonths(-2), Y = 200 },
            
new
{ X = DateTime.Now.AddMonths(-1), Y = 300 },
            
new { X = DateTime.Now, Y = 500 }
       };
    }
}

Chart view

Here is our chart view. All we do in this view is defining chart, giving it a nice look and then displaying it as image.

@model dynamic
 
@{
    View.Title =
"Chart"
;
    Layout =
"~/Views/Shared/_Layout.cshtml"
;
 
   
var key = new
Chart(400, 200, ChartTheme.Blue)
                .AddTitle(
"Price enquiries"
)
                .DataBindTable(Model,
"X"
)
                .Write(
"png");
}

When we run our application we can see that chart is rendered correctly. We can also add some mark-up to view but still everything works. Write() method is the evil here. It guarantees that response contains only the image of chart with all headers needed and nothing more. Seems like we don’t need view here.

Let’s output the image in controller action and remove view.

public ActionResult Chart()
{
   
var model = new ChartModel
();
   
var
data = model.GetChartData();

   
new Chart(400, 200, ChartTheme
.Blue)
        .AddTitle(
"Price enquiries"
)
        .DataBindTable(data,
"X"
)
        .Write(
"png"
);

   
return null;
}

I think this solution is better because we have not so much code and therefore we don’t really have a point to split part of this short code to view. Also we have one file less in our project now.

Our first ASP.NET MVC chart

When you run the code you should see something like this in browser window. This nice blue design is not my own work that I don’t want you to tell about. I used ChartTheme.Blue when instantiating Chart and this is the way I can tell to chart what kind of theme to use.

ASP.NET MVC chart in action

Okay, my chart looks very nice to me!

Conclusion

Charting is made very convenient in ASP.NET MVC 3 Beta. We can use Chart class that has good API with fluent syntax and it is extremely easy to use. To make chart look nice and cool we used built-in theme. We used no hacks bridging ASP.NET Forms and ASP.NET MVC frameworks and our code is simple and clean.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    14 thoughts on “ASP.NET MVC 3 Beta: Built-in support for charts

    • October 10, 2010 at 1:24 pm
      Permalink

      You can return void from Chart method instead of ActionResult.

    • October 13, 2010 at 4:27 pm
      Permalink

      Thanks for feedback smirnov.os and PabloBlamirez!

      smirnov.os – just made fix to the code in repository. PabloBlamirez – I will write separate post about how to test actions with output like this. Chart is now only new thing that is added to helpers, there are some components more. As soon as I know how the other components work I will publish here posting about action results that you can use to make your controllers testable.

    • October 18, 2010 at 7:24 pm
      Permalink

      Does not work. I get this error “A generic error occurred in GDI+.”

    • October 27, 2010 at 12:36 am
      Permalink

      Much clearer usage than the examples in the (admittedly beta) MVC 3 tutorial example. Thanks.

    • May 27, 2011 at 7:05 am
      Permalink

      Thanks for quetsion, dotnetmvcbeginner. You should be able to do it with data series if I’m correct.

    • May 27, 2011 at 1:21 pm
      Permalink

      Thanks for the quick reply DigiMortal..If you don’t mind, can you elaborate more on your point?

    • May 31, 2011 at 2:02 pm
      Permalink

      Now I can give both the y1 and y2 values but this time I have to even display the y1 and y2 (both) labels on top of the bar. By using the “Label” property of Series, i can either show y1 or y2 but not both at a time. Also, I have to display it on hte top of the bars but not inside the bars.
      Something like this…
      |
      | y1 y2
      | _______
      | |_______|
      |
      |_______________

      Here’s my code so far for .cs and .aspx pages..

      protected void Page_Load(object sender, System.EventArgs e)
      {
      // Populate series data
      Chart1.Series[“Tasks”].Points.AddXY(1, 0, 100);
      Chart1.Series[“Tasks”].Points.AddXY(2, 0, 100);

      Chart1.Series[“Progress”].Points.AddXY(1, 10, 50);
      Chart1.Series[“Progress”].Points.AddXY(2, 20, 60);

      // Set axis labels
      Chart1.Series[“Tasks”].Points[2].AxisLabel = “Fixed Inc”;
      Chart1.Series[“Tasks”].Points[3].AxisLabel = “Equity”;

      // Set Range Bar chart type
      Chart1.Series[“Tasks”].ChartType = SeriesChartType.RangeBar;
      Chart1.Series[“Progress”].ChartType = SeriesChartType.RangeBar;

      // Set Y axis Minimum and Maximum
      Chart1.ChartAreas[“ChartArea1”].AxisY.Minimum = 0;
      Chart1.ChartAreas[“ChartArea1”].AxisY.Maximum = 100;
      }
      ______________________________________________________

    • Pingback:ASP.NET MVC 3 Beta: Caching charts | Gunnar Peipman - Programming Blog

    • Pingback:ASP.NET MVC 3 Beta: Simple image manipulations using WebImage helper | Gunnar Peipman - Programming Blog

    • August 13, 2016 at 12:59 pm
      Permalink

      No, I don’t think so. Generating of PDF is usually the topic of third-party components.

    Leave a Reply

    Your email address will not be published. Required fields are marked *