Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

c# - Showing System.Web.Helpers.Chart in a partial view from the model

So I was trying out the Chart helpers in the System.Web.Helpers namespace.

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

I make the chart in a .cshtml view but I wanted to keep it in the ViewModel instead.

No problem except for when I'm trying to render it as a smaller image in the website.

I thought the cleanest solution would be to create one shared partial view to render graphs from models

_graph.cshtml

@model System.Web.Helpers.Chart

@Model.Write()

And then render this partial view somehow in the proper websites. I tried a few versions but can't seem to get it to work.

Website.cshtml

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

This doesn't work and I'm not certain how to do this. Only think I can think of now is making all models with charts inherit an Interface that exposes Chart and let that be the model for _graph.cshtml.

<img src="_graph.cshtml" />

But not sure if the this uses the Model.

Any opinions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<div>
    <h2>Some header above a graph</h2>
    <img src="@Url.Action("DrawChart")" />
</div>

and then you could have a controller action:

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

and a corresponding view that will draw the chart (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();
}

and the rendered result:


enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...