no

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: http://www.asp.ne...

I was working on a project that requires showing a graph, fortunately there's already a built in graph helper in mvc3: http://www.asp.net/web-pages/tutorials/data/7-displaying-data-in-a-chart.

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)
 .AddSeries(
  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);
            chart.Write("png");
            return null;
        }
The View, this will render the image:
 <img src="@Url.Action("CustomReport", "Graph", new { key = ViewBag.GraphKey })" />
And that's it :-)

Related

c# 4627994236488214961

Post a Comment Default Comments

2 comments

Ravi said...

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

Unknown 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.

item