在模型的局部视图中显示System.Web.Helpers.Chart

时间:2012-03-13 13:50:14

标签: c# html asp.net-mvc-3 razor charts

所以我在System.Web.Helpers命名空间中尝试了图表助手。

根据http://www.asp.net/web-pages/tutorials/data/7-displaying-data-in-a-chart

我在.cshtml视图中制作图表,但我想将其保留在ViewModel中。

没问题,除非我试图将其渲染为网站中较小的图像。

我认为最干净的解决方案是创建一个共享局部视图来渲染模型中的图形

_graph.cshtml

@model System.Web.Helpers.Chart

@Model.Write()

然后在适当的网站中以某种方式呈现此部分视图。我尝试了几个版本,但似乎无法让它工作。

Website.cshtml

<div>
    <h2>Some header above a graph</h2>
    <img src="@Html.Partial("_graph", Model.TheChart)" />
</div>

这不起作用,我不确定如何做到这一点。只有我认为现在才能想到的是,所有带图表的模型都会继承一个公开Chart的接口,并让它成为_graph.cshtml的模型。

<img src="_graph.cshtml" />

但不确定这是否使用了模型。

有什么意见吗?

2 个答案:

答案 0 :(得分:11)

<div>
    <h2>Some header above a graph</h2>
    <img src="@Url.Action("DrawChart")" />
</div>

然后你可以有一个控制器动作:

public ActionResult DrawChart()
{
    MyViewModel model = ...
    return View(model);
}

以及绘制图表的相应视图(DrawChart.cshtml):

@model MyViewModel

@{
    // TODO: use the data from the model to draw a chart

    var myChart = new Chart(width: 600, height: 400)
        .AddTitle("Chart Title")
        .AddSeries(
            name: "Employee",
            xValue: new[] {  "Peter", "Andrew", "Julie", "Mary", "Dave" },
            yValues: new[] { "2", "6", "4", "5", "3" })
        .Write();
}

和渲染结果:


enter image description here

答案 1 :(得分:0)

<div>
<h2>Some header above a graph</h2>
<img src="@Url.Action("DrawChart")" />
</div>

public ActionResult DrawChart()
{
MyViewModel model = ...
return View(model);  

}

!!!将Model参数发送到DrawChart

更改为

<div>
    <h2>Some header above a graph</h2>
    <img src="@Url.Action("DrawChart",Model)" />
</div>

public ActionResult DrawChart(MyViewModel _MyViewModel )
{
    MyViewModel model = MyViewModel ;
    return View(model);
}

MyViewModel为Null

向那些知道的人寻求建议。