简体   繁体   中英

create a data structure in controller using c# and pass it into view

I am new to asp.net MVC4. i am using doing some chart function in my asp.net mvc application.

i searched and found a js library called Chart.js

http://www.chartjs.org/docs/#line-chart-data-structure the data structure is like below:

 var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", fillColor: "rgba(220,220,220,0.2)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: [65, 59, 80, 81, 56, 55, 40] }, { label: "My Second dataset", fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", data: [28, 48, 40, 19, 86, 27, 90] } ] }; 

i am trying to read data from db in my controller and pass this data into the view but always failed to display the chart.

i tried this in controller:

 int[] intArray = new int[7]; intArray[0] = 34; intArray[1] = 1; intArray[2] = 2; intArray[3] = 23; intArray[4] = 11; intArray[5] = 11; intArray[6] = 11; ViewBag.proinfo = Json(intArray, JsonRequestBehavior.AllowGet).Data; 

and then in view:

  { label: "My Second dataset", fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", ViewBag.proinfo } 

but this not work for me.the chart can not display.

how to create this data structure in c# controller and pass it to view?

many thanks!

you can easily assign value in ViewBag.proinfo

ViewBag.proinfo = intArray;

you forgot to define data in json in View

{
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data:ViewBag.proinfo
}

try this:
in controller:

ViewBag.proinfo = intArray

in view

  { label: "My Second dataset", fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", data: @Html.Raw(Json.Encode(ViewBag.proinfo)); } 
I assume u're using MVC Razor symtax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM