It is absolutely possible. Let's start by creating a new view model to represent the chart data.
public class ChartSeriesData
{
public string[] XValues { set; get; }
public string[] YValues { set; get; }
public string Name { set; get; }
}
public class MyChartData
{
public List<ChartSeriesData> Series { set; get; }
public string Name { set; get; }
}
And in your Action method, create an object if the MyChartData
class, Set the different property values and send it to the view.
public ActionResult MyChart()
{
var vm= new MyChartData { Name = "MyChartTitle",Series = new List<ChartSeriesData>()};
vm.Series.Add(new ChartSeriesData
{
Name = "View",
XValues = new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
YValues = new[] { "2", "6", "4", "5", "3" }}
);
vm.Series.Add(new ChartSeriesData
{
Name = "Downloads",
XValues = new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
YValues = new[] { "1", "2", "6", "5", "3" }
});
return View(vm);
}
Now in your view ,which is strongly typed to a our MyChartData
view model, we will iterate through the Series property and call the AddSeries
method.
@model ReplaceWithYourNameSpaceHere.MyChartData
@{
var myChart = new Chart(width: 600, height: 400)
.AddTitle(Model.Name);
foreach (var item in Model.Series)
{
myChart.AddSeries(name: item.Name, xValue: item.XValues, yValues: item.YValues);
}
myChart.Write();
}
If you want to include the chart in another razor view, you can use an image tag and set the src
attribute value to MyChart action method.
<img src="@Url.Action("MyChart","Home")" alt="Some alt text" />
Assuming MyChart
action method exists in HomeController
.