A Model contains, amongst other properties, a method which returns an MSChart as a MemoryStream.
In my View I copy the MemoryStream to TempData[“Chart”] and then use URL.Action() to call a controllers action to return a FileContentResult using the MemoryStream from TempData.
In the Model
public MemoryStream ViewerChart()
{
Chart chart = new Chart();
:
:
using (MemoryStream memStream = new MemoryStream())
{
chart.SaveImage(memStream, ChartImageFormat.Jpeg);
return memStream;
}
}
In the View
@{
TempData["Chart"]= Model.ViewerChart();
}
<img alt="Chart" src="@Url.Action("RenderChart")" />
In the Controller
public ActionResult RenderChart()
{
MemoryStream ms = TempData["Chart"] as MemoryStream;
return File(ms.ToArray(), "image/jpeg");
}
Despite working OK, this all seems a bit nasty to me, particularly the use of TempData
Is there a better way?
The acedemic way would be to retrieve the model object again in the
RenderChartaction and return the chart image to the view.But i think its a valid approach to store the image in
TempDatafor reducing database roundtrips and boosting performance.Maybe its even unnecessary to improve the performance. The database will have the data available in its cache when reading it the second time and the additional 10ms needed to fetch the data again might not be noticeable by the user.
At least
TempDataseems to be the right store because the value is deleted from the collection when its read by theRenderChartaction.