Вопрос

Im kinda new to web apps and the world of javascript, jquery, json, knockout, etc, etc Im trying to do something real simple but not getting to work. I want to pass data from controller to view to build a plot using morris.js.

I google it and tried several attempts, none succeeded.

The view recieves something like this to buils the graph:

<script>
    new Morris.Line({
    // ID of the element in which to draw the chart.
    element: 'myfirstchart',
    // Chart data records -- each entry in this array corresponds to a point on
    // the chart.
    data: [
    { year: '2008', value: 20 },
    { year: '2009', value: 10 },
    { year: '2010', value: 5 },
    { year: '2011', value: 5 },
    { year: '2012', value: 20 }
    ],
    // The name of the data record attribute that contains x-values.
    xkey: 'year',
    // A list of names of data record attributes that contain y-values.
    ykeys: ['value'],
    // Labels for the ykeys -- will be displayed when you hover over the
    // chart.
    labels: ['Value']
});
</script>

Now i want to send the data from the controller using the viewbag or something else. For what i understood JSON is the most correct way, just dont know how to use it.

Can you show me how please?

Это было полезно?

Решение

You can have a viewmodel that represents your data, then build a collection of it in your controller. You can then call it via ajax and return it as a json object.

The ViewModel

public class YearlyStat {
    public int Year {get;set;}
    public int Value {get;set;}
}

Build the data in the controller like this:

public ActionResult Statistics() {
    // most probably the values will come from a database
    // this is just a sample to show you 
    // that you can return an IEnumerable object
    // and it will be serialized properly
    var stats = new List<YearlyStat> {
        new YearlyStat { Year=2008, Value=20},
        new YearlyStat { Year=2009, Value=10},
    }
    return Json(stats,JsonRequestBehavior.AllowGet);
}

Then consume it like this:

$.get('@Url.Action("Statistics")', function(result){
    new Morris.Line({
        data: result,
    });
});

Другие советы

You could use .ajax to retrieve data from controller, and use it in your script. You can't use ViewBag in your javascripts on client side.

You can use jquery for get request from client side:

<script>
   $(function() {
     $.get('@Url.Action("GetDataForPlot")', function(response) {
       // put your code for drawing plot
       // response is your data from controller to use in plot
     });
   });
</script>

And controller

public ActionResult GetDataForPlot() {
    var data= new List<Stats> {
        new Stats{ Year=2010, Value=50},
        new Stats{ Year=2011, Value=100},
        new Stats{ Year=2012, Value=150},
    }
    return Json(data, JsonRequestBehavior.AllowGet);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top