74

Scott Gu just posted about a new set of charting controls being distributed by the .NET team. They look incredible: http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx

The million dollar question is ... will they work with MVC, and if so, when?

Kyle West
  • 8,934
  • 13
  • 65
  • 97

6 Answers6

93

You can use the chart controls in two ways:

Generating the Image from a Controller

By generating the chart and returning it as an image from an action (as Chatuman is referring to I think):

Chart chart = new Chart();
chart.BackColor = Color.Transparent;
chart.Width = Unit.Pixel(250);
chart.Height = Unit.Pixel(100);

Series series1 = new Series("Series1");
series1.ChartArea = "ca1";
series1.ChartType = SeriesChartType.Pie;
series1.Font = new Font("Verdana", 8.25f, FontStyle.Regular);
series1.Points.Add(new DataPoint { 
                AxisLabel = "Value1", YValues = new double[] { value1 } });
series1.Points.Add(new DataPoint {
                AxisLabel = "Value2", YValues = new double[] { value2 } });
chart.Series.Add(series1);

ChartArea ca1 = new ChartArea("ca1");
ca1.BackColor = Color.Transparent;
chart.ChartAreas.Add(ca1);

using (var ms = new MemoryStream())
{
    chart.SaveImage(ms, ChartImageFormat.Png);
    ms.Seek(0, SeekOrigin.Begin);

    return File(ms.ToArray(), "image/png", "mychart.png");
}

WebForms Style

This way you just include the chart in your .aspx views (just like with traditional web forms). For this you'll have to hook up the relevant bits in your web.config

<controls>
    ...
    <add tagPrefix="asp"
         namespace="System.Web.UI.DataVisualization.Charting"
         assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>

<httpHandlers>
    ...
    <add path="ChartImg.axd"
         verb="GET,HEAD"
         validate="false"
         type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpHandlers>

<handlers>
    ...
    <add name="ChartImageHandler"
         preCondition="integratedMode" 
         verb="GET,HEAD"
         path="ChartImg.axd"
         type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>

You can't run code inside the DataPoint elements when building the chart, so to hook up your data you'll need a method in the View class. This works ok for me. Working this way makes the control render a URL to an image generated by the chart control http handler. In your deployment you'll need to provide a writable folder for it to cache the images.

* VS 2010 / .NET 4 Support *

To get this working in .NET 4 you need to change the chart references to version 4.0.0.0 with the appropriate public key token.

Also it seems that the chart control now generates urls to the current request path rather than the request route. For me this meant that all the chart requests resulted in 404 errors because /{Controller}/ChartImg.axd and equivalents were blocked by routes. To fix this I added extra IgnoreRoute calls that cover my usages - a more general solution would be better:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("ChartImg.axd/{*pathInfo}");
    routes.IgnoreRoute("{controller}/ChartImg.axd/{*pathInfo}");
    routes.IgnoreRoute("{controller}/{action}/ChartImg.axd/{*pathInfo}");
...
Simon Steele
  • 11,558
  • 4
  • 45
  • 67
  • 12
    +1 - nice. 2 small changes: `MemoryStream ms = new MemoryStream()` should be in a `using` block, and MVC controller has helper methods for returning files - instead of `new FileStreamResult` you can do `return File(ms.ToArray(), "image/png", "mychart.png")` – Keith Jan 20 '10 at 13:26
  • 1
    Added information for getting this working in .NET 4 - took me ages to figure out the routes thing! – Simon Steele Mar 30 '10 at 17:29
  • 4
    I just posted an updated for .net 4.0 version of the chart samples on my blog and threw in 2 additional projects -- ChartsWithMVC and ChartsWithoutWebForms which both basically render the chart as an image and return it. http://develocity.blogspot.com/2010/04/aspnet-chart-controls-without-web-forms.html – Dave Haynes Apr 26 '10 at 18:10
  • 1
    Is there any other way , so that I can used Microsoft charts interactive and ajax support ?. I m using MVC 4 – kbvishnu Aug 01 '12 at 14:59
  • Additional info that may help someone: If your charts are within an area, you need to add the ignores (context.Routes.Ignore("{controller}/{action}/ChartImg.axd/{*pathInfo}")) to RegisterArea method too – Fiona - myaccessible.website Aug 05 '13 at 15:28
11

For folks who want to use charting control with MVC 3 using Razor engine see the following link

How to use MS Charts with MVC3 with Razor

Sarath
  • 2,719
  • 1
  • 31
  • 39
2

You can already use them with MVC all you have to do is render them as images

Chatu
  • 4,688
  • 3
  • 22
  • 15
1

Make a Usercontrol instead and give it the full Chart object and let it render it self:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Web.UI.DataVisualization.Charting.Chart>" %>
<%
    Model.Page = this.Page;
    var writer = new HtmlTextWriter(Page.Response.Output);
    Model.RenderControl(writer);
%>

name it Chart.ascx and put it in your Shared view folder.

now you will get all extra html, like image map etc. for free.. as well as caching.

in your Controller:

public ActionResult Chart(){
 var c = new Chart();
 //...
 return View(c);
}

in your View:

<% Html.RenderPartial("Chart", Model); %>
Carl Hörberg
  • 5,973
  • 5
  • 41
  • 47
  • Im getting a number of errors I have NEVER seen before using this method, the first of which is `Error executing child request for ChartImg.axd.` - can you help with this? – Jimbo Apr 26 '10 at 13:34
  • Users suggested adding `` to the web.config under the `` section, however this then causes another error `Session state has created a session id, but cannot save it because the response was already flushed by the application.` - did this happen in your implementation as well? – Jimbo Apr 26 '10 at 13:37
  • do use .NET 4.0 or 3.5? if you use 3.5 you have to add the stuff to web.config as http://stackoverflow.com/questions/319835/new-asp-net-charting-controls-will-they-work-with-mvc-eventually/320891#320891 suggests. – Carl Hörberg Apr 27 '10 at 08:09
  • if you use .NET 4.0 add the following: and – Carl Hörberg Apr 27 '10 at 08:09
  • YES thanks Carl! Works for me in MVC 4 and NET 4.5 VS2012. An easy way to generate the web.config elements is simply use the Solution Explorer to add a new WebForm.aspx item to the MVC 4 project; then drag from the Toolbox a Chart Control onto the aspx design surface. And, to App_Start/RouteConfig.cs, add the code to ignore the routes as shown by Simon Steele. – subsci Sep 13 '13 at 10:31
1

This article worked it out best for me:

http://www.codecapers.com/post/Build-a-Dashboard-With-Microsoft-Chart-Controls.aspx

Doesn't give errors about 'Object not set to an instance of an object' or 'Session id was available but the response stream has been flushed' (not the exact wording of the errors).

I wasn't willing to just render them as an image because if you're doing drilldowns or tooltips or other click actions on the chart, then rendering as an image doesn't preserve any of that.

The key for my needs was to put the chart(s) into a model, pass the model to the view (or partial view) and put an asp:panel in the view and add the chart(s) to the panel in the view markup.

By the way, this was with VS.net 2008 and MVC 2 on Sept. 3, 2010 (dates was something that I found important when searching for answers because of the changes that are continually happening to MVC).

Darryl
  • 11
  • 1
0

I have been testing with MVC and so far it looks like it is working with MVC.

Picflight
  • 3,832
  • 13
  • 61
  • 90