ASP.NET MVC:从模型中显示多个图表

时间:2015-03-21 16:26:33

标签: c# asp.net asp.net-mvc charts

我喜欢带有多个图表的网页。图表的数据驻留在我的模型中,我在控制器中创建并传递给视图。但是,我在视图中创建图表时遇到了麻烦。

Microsoft已创建此类以在MVC中创建基本图表: https://msdn.microsoft.com/en-us/library/system.web.helpers.chart%28v=vs.111%29.aspx

它有它的怪癖。例如,如果要显示多个图表,则需要从视图调用回控制器。 (在#34;显示网页内的图表":http://www.asp.net/web-pages/overview/data/7-displaying-data-in-a-chart

部分中对此进行了解释

基本上你需要使用@ Url.Action(" MakeChart")作为HTML图像标记的src。但是,如何将视图中的模型传递回控制器以创建图像?如果我尝试通过@ Url.Action传递模型,则模型是空引用。

1 个答案:

答案 0 :(得分:2)

哇我试着按照他们给出的指示而烦恼。

最后我不得不这样做。

控制器

public ActionResult MakeChart()
{
    return this.View(new Employees());
}

public ActionResult ShowChart()
{
    return this.View(new Employees());
}

ShowChart.cshtml

@model MyDashboard.Models.Employees
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Chart Example</title>
</head>
<body>
    <h1>Chart Example</h1>
    <p>
        The following chart is generated by the <em>ChartArrayBasic.cshtml</em> file, but is shown
        in this page.
    </p>
    @*<p><img src="MakeChart.cshtml" /> </p>*@
    <img src="@Url.Action("MakeChart", new {  model = @Model })" />
</body>
</html>

MakeChart.cshtml

@model MyDashboard.Models.Employees

@{
    var myChart = new Chart(width: 600, height: 400)
        .AddTitle("Chart Title")
        .AddSeries(
            name: "Employee",
            xValue: @Model.Names,
            yValues: @Model.Ids)
        .Write();
}

Model = Employees

public class Employees
{
    public string[] Names { get; set; }

    public string[] Ids { get; set; }

    public Employees()
    {
        this.Names = new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" };
        this.Ids = new[] { "2", "6", "4", "5", "3" };
    }
}

结果

enter image description here