سؤال

I'm trying to create charts in a view , the content (name/ series/type etc) will all be determined by the controls a user selects in the view.

As long as I load an already created chart all is fine, for example:

Inside my View:

     <controls above my graph>

  <img src="@Url.Action("StatusGraph")"/>

     <controls below my graph>

Inside the Controller

    //Creates status graph as specified by the controls in parent partial view or using          defaults
     public ActionResult StatusGraph(){
         return View();
     }

And finally the StatusGraph View: (the generic chart this microsoft tutorial uses as example)

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

As I said this works perfectly and actually renders the chart inside the parent view as opposed in its own separate window (really microsoft, why?), However as soon as I try to extend the StatusGraph method to accept parameters (simply the chart title to start with) and pass that to StatusGraph I get a 404 error when the browser tries to load the picture.

When I set breakpoints in the extended StatusGraph method where I try to pass the title to the view, the code never stops, as if it is never called.

My question is: how can I make this work? How can I pass data from the view to an action to another view.

Thank you!

هل كانت مفيدة؟

المحلول

You could/should use a view model:

public class MyViewModel
{
    public string Title { get; set; }
}

and then:

public ActionResult StatusGraph(MyViewModel model)
{
    return View(model);
}

and finally:

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

and when rendering the chart pass the value:

<img src="@Url.Action("StatusGraph", new { title = "Chart title" })"/>

Of course the values could also be defined in your controller action instead of passing them as parameters to the img source:

public ActionResult StatusGraph()
{
    var model = new MyViewModel
    {
        // TODO: could come from a database or something
        Title = "Chart title"
    };
    return View(model);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top