1

I'd like a webpage with multiple charts. The data for the charts resides in my model, which I create in the controller and pass to the view. But, I'm running into trouble creating the charts within the view.

Microsoft has created this class to create basic charts within MVC: https://msdn.microsoft.com/en-us/library/system.web.helpers.chart%28v=vs.111%29.aspx

It has it's quirks. For instance, if you want to display multiple charts you need to call from the view back to a controller. (It's explained here in the section "Displaying Charts Inside a Web Page": http://www.asp.net/web-pages/overview/data/7-displaying-data-in-a-chart)

Basically you need to use @Url.Action("MakeChart") as the src to an HTML image tag. But, how can you pass your model within the view back to the controller to create the image? If I try to pass the model through @Url.Action, the model is a null reference.

1 Answer 1

2

Wow I tried to follow the directions they gave and was stumped too.

At the end I had to do this.

Controller

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" };
    }
}

Result

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.