I am trying to display MVC charts as shown in Creating a HTML5 Chart Helper Extension for ASP.NET MVC 4. I have the standard project working but I can't get multiple graphs to show up at once in partial views called by a single view.
I will skip reviewing the ChartExtensions.cs
and HelperModel.cs
classes since they are covered in the article above.
I created a controller with a few views:
public class WelcomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Creating your own HtmlHelper library";
var data = WelcomeHelper.GetData1();
return View(data);
}
public ActionResult DisplayAllGraphs()
{
ViewBag.Message = "Show all charts";
var dataSet = new DataGroup();
dataSet.Datas.Add(WelcomeHelper.GetData1());
dataSet.Datas.Add(WelcomeHelper.GetData2());
return View(dataSet);
}
public ActionResult PartialDisplayGraphs(TwoDimensionalData data)
{
ViewBag.Message = "Chart by request";
return View(data);
}
}
I populate it with a quick helper class
public class WelcomeHelper
{
public static TwoDimensionalData GetData1()
{
var data = new TwoDimensionalData();
data.Data.Add(new int[] { 2000, 3045 });
data.Data.Add(new int[] { 2001, 7045 });
data.Data.Add(new int[] { 2002, 9045 });
data.Data.Add(new int[] { 2003, 13045 });
data.Data.Add(new int[] { 2004, 15045 });
data.Id = 1;
return data;
}
public static TwoDimensionalData GetData2()
{
var data = new TwoDimensionalData();
data.Data.Add(new int[] { 2005, 18045 });
data.Data.Add(new int[] { 2006, 20845 });
data.Data.Add(new int[] { 2007, 23045 });
data.Data.Add(new int[] { 2008, 20345 });
data.Data.Add(new int[] { 2009, 23405 });
data.Id = 2;
return data;
}
}
I attempt to display all the graphs with DisplayAllGraphs.cshtml
@model PostingGraphs.Models.DataGroup
@{
ViewBag.Title = "DisplayAllGraphs";
}
<h2>@ViewBag.Message</h2>
<section>
@Html.Partial("PartialDisplayGraphs", data)
</section>
and the PartialDisplayGraphs.cshtml
called for partial view is
@model PostingGraphs.Models.TwoDimensionalData
@using PostingGraphs.Extensions
@using (Html.BeginForm())
{
<label>Model ID: @Model.Id</label>
@Html.Chart("sampleChart" + Model.Id, Model.Data, "Year", "Hits in Thousands")
}
@section Scripts
{
<script type="text/javascript">
$(function () {
barChart();
});
</script>
}
What I get is a series of <section>
s with the label Model ID: # where the # coincides correctly with the ID of the data being sent as the model. That I do not get is a chart, although the section is spaced as expected.
Am I missing something? Is this a problem with identifiers within the code for the chart extensions creating the javascript?
EDIT: Added unique identifier for canvas ID to include index of data points. Changed form within form issue.