How to render a Chart object in a view in MVC3

I was working on a project that requires showing a graph, fortunately there's already a built in graph helper in mvc3:

Tried the tutorial in link above and was able to display the graph, but I've encountered a problem, I would like to show the graph inside a tabpanel, wherein tab1 = grid, tab2 = graph.

Unfortunately, there's no other way but to issue another http request that will call an action method from a controller to return a FileContentResult, or could be set to write an image in the stream. I chose the latter. In my case I need to execute a query against the database for the grid and for the graph, of course we don't want to execute 2 queries so the solution is to store the image in a cache assign a unique key, save in a ViewBag(key) and retrieve/render the image in a view.

First Controller, where we store the graph in the cache and refer to it later via a random key.
public ActionResult Search() {
var chart = new Chart(width: 600, height: 500)
  chartType: "bar",
  xValue: new[] {"10 Records", "20 Records", "30 Records", "40 Records"},
  yValues: new[] {"50", "60", "78", "80"});

var r = new Random();
ViewBag.GraphKey = r.Next().ToString();
chart.SaveToCache(ViewBag.GraphKey, 1, false);
return View();
Controller that will retrieve the image via the unique key
 public ActionResult CustomReport(string key)
            var chart = Chart.GetFromCache(key);
            return null;
The View, this will render the image:
 <img src="@Url.Action("CustomReport", "Graph", new { key = ViewBag.GraphKey })" />
And that's it :-)
How to render a Chart object in a view in MVC3 How to render a Chart object in a view in MVC3 Reviewed by Edward Legaspi on Monday, February 13, 2012 Rating: 5


Ravi said...

Nice stuff, typical chart issue is addressed here in MVC world

kuldeep soni said...

while using this code in my application i m getting error-Object reference not set to an instance of an object.and key value cannot be null.please help.

Powered by Blogger.