Kurkula Kurkula - 9 months ago 76
ASP.NET (C#) Question

Asp.net mvc chart destroys page data

I used asp.net mvc chart control to display chart in middle of my page. I have gone through some tutorials here

When I added my chart with the below code all page code is destroyed and only chart is displayed on page. I tried to pull chart from partial view and also tried to paste in between the code. But still I see only the chart and not the combination of my page output and chart. I also tried with

<img src="mypage.cshtml" />

@{
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();
}

Answer Source

It is better to keep your concerns separated and keep logic in the controller, which can be rendered by the View, rather than having logic in the View or a partial view.

In your controller I would have an action that returns a FileResult:

public FileResult 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" });

    return File(myChart.ToWebImage().GetBytes(), "image/jpeg");
}

Then in you view just call it using, for example:

<h1>Chart Example</h1>
<p>
    Your html markup etc.
</p>
<img src="@Url.Action("Chart")" />