Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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.

Source code

If you want to play with my solution then please feel free to download source code from my source code repository in GitHub.

Source code @ GitHub Source code repository
GitHub

Chart example is located inExperiments.AspNetMvc3NewFeatures solution. Project name is Experiments.AspNetMvc3NewFeatures.Razor. 

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 3: Charting with Razor

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.

Comments

smirnov.os said:

You can return void from Chart method instead of ActionResult.

# October 10, 2010 9:24 AM

DigiMortal said:

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 13, 2010 12:27 PM

bennyb said:

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

# October 18, 2010 3:24 PM

Gene said:

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

# October 26, 2010 8:36 PM

dotnetmvcbeginner said:

Hi,

I am new to MVC 3 and I want to implement the RangeBarChart control in MVC 3. I do not know how to give two Y-values for an X-value. Below is the link of an image for my output where the bar chart changes based on the selected value of a dropdown.

www.dotnetspider.com/.../285038-261852-photo.JPG

Thanks!

# May 26, 2011 4:52 PM

DigiMortal said:

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

# May 27, 2011 3:05 AM

dotnetmvcbeginner said:

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

# May 27, 2011 9:21 AM

DigiMortal said:

Take a look at this tutorial about WebMatrix charts:

www.asp.net/.../7-displaying-data-in-a-chart

This is exactly same stuff that is used here. You point of interest should be the series collection of chart. Here's the full documentation of chart class:

msdn.microsoft.com/.../system.web.helpers.chart(v=VS.99).aspx

# May 30, 2011 6:11 AM

dotnetmvcbeginner said:

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;

}

______________________________________________________

<asp:CHART id="Chart1" runat="server" BackColor="White" Width="412px" Height="296px" BorderlineDashStyle="NotSet" Palette= "None" BackGradientStyle= "None" BorderWidth="0" BorderColor="White" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)">

<series>

<asp:Series YValuesPerPoint="2" Name="Tasks" ChartType="RangeBar" CustomProperties="PointWidth=0.4" BorderColor="Silver" Color="Silver"></asp:Series>

<asp:Series YValuesPerPoint="4" Name="Progress" ChartType="RangeBar" CustomProperties="PointWidth=0.4, DrawSideBySide=false" IsValueShownAsLabel="true" BorderColor="Maroon" Color="Maroon"></asp:Series>

</series>

<chartareas>

<asp:ChartArea Name="ChartArea1" BorderDashStyle= "NotSet" BackSecondaryColor="White" BackColor="White">

<position Y="6" Height="80" Width="87" X="5"></position>

<axisy LineColor="64, 64, 64, 64" IsStartedFromZero="False" Enabled="False">

<LabelStyle IsEndLabelVisible="true" Font="Trebuchet MS, 8.25pt, style=Bold" />

</axisy>

<axisx LineColor="64, 64, 64, 64">

<LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" IsEndLabelVisible="False" />

</axisx>

</asp:ChartArea>

</chartareas>

</asp:CHART>

# May 31, 2011 10:02 AM

RAJU said:

How will I change Chart Type like Bar, Pie etc.

# March 15, 2012 5:53 AM