Passing Chart Series from Controller to Razor View

2019-01-27 04:38发布

问题:

I am u sing asp.net mvc 4 and placed a chart on view. i want to load its series from controller. how can i do that ? please can anyone explain it with piece of code.

Index View

@{
var myChart = new Chart(width: 600, height: 400)
    .AddTitle("Chart Title")
    .AddSeries(
        name: "Views",
        xValue: new[] {  "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
        yValues: new[] { "2", "6", "4", "5", "3" })
    .AddSeries(
        name: "Downloads",
        xValue: new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
        yValues: new[] { "1", "2", "3", "4", "5" })

        .Write();
}

Controller

    public ActionResult Index()
    {
        return View();
    }

回答1:

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.