Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Friday, May 18, 2012

Create Chart using Chart Helper in ASP.NET MVC 3

To insert chart into a web page in ASP.NET MVC3, you can use Chart Helper which included in MVC 3. It will generate image chart dynamically that you can use generated chart to be the image soruce in image tag.
In cshtml page has an image element as follows:
<!-- It will refer to /[Name]Controller/MyChart, and send back an image chart. -->
<img src="@Url.Action("MyChart")" alt="SimpleChart" />
Under your controller class, you create a MyChart method that return String in an image format (jpg/png) as an action.
public ActionResult MyChart()
{
     var bytes = new Chart(width: 400, height: 200)
          .AddSeries(
               chartType: "bar",
               xValue: new[] { "Math", "English", "Computer", "Urdu" },
               yValues: new[] { "60", "70", "68", "88" })
          .GetBytes("png");
     return File(bytes, "image/png");
}
After that, you will get the chart image when requesting MyChart action.

2 comments:

  1. How to Display it as an image ?

    ReplyDelete
    Replies
    1. From this example, you will got it as a dynamic PNG image.

      Delete