[英]Passing Dictionary object from controller to Javascript
我在将字典对象从控制器传递到视图中的javascript时遇到了麻烦。 我正在使用ASP .Net MVC3,并且尝试使用数据库中的数据制作一些图表/图形,我发现了HighCharts javascript,并且正在尝试使用它。 这是示例:
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Stacked column chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
tooltip: {
formatter: function() {
return ''+
this.series.name +': '+ this.y +' ('+ Math.round(this.percentage) +'%)';
}
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
});
});
});
我想用字典填充系列变量,这是即时通讯使用的方法:
public ActionResult GetSeries()
{
var series= new Dictionary<string, int[]> {
{ "pa", new int[]{1,2,3,4,5} },
{ "papa", new int[]{1,2,3,4,5} },
{ "papapa", new int[]{1,2,3,4,5} },
};
return Json(series, JsonRequestBehavior.AllowGet);
}
但它返回类似:
{“ pa”:[1,2,3,4,5],“ papa”:[1,2,3,4,5],“ papapa”:[1,2,3,4,5]}
因此它的语法与javascript中的语法不同,在每个字段之前都有名称和数据
顺便说一句,即时通讯使用此来填充数据
$.getJSON('@Url.Action("GetSeries)', function(series) {
...
series: series
...
});
最好的问候,海尔德
它返回的是关联数组在JavaScript中的外观。 根据顶部示例中的JavaScript,您真正想要的是对象的数组或列表:
var series= new[] {
new { name="pa", data=new int[]{1,2,3,4,5} },
new { name="papa", data=new int[]{1,2,3,4,5} },
new { name="papapa", data=new int[]{1,2,3,4,5} },
};
return Json(series, JsonRequestBehavior.AllowGet);
我将创建一些视图模型(这只是一个类的奇特名称,该类包含以适当的格式和结构显示在视图中所需的所有数据),并将其作为JSON消息返回。
public class SeriesViewModel
{
public string name { get; set; }
public int[] data { get; set; }
}
public class GetSeriesViewModel
{
public string[] categories { get; set; }
public SeriesViewModel[] series { get; set; }
}
只需添加需要以JSON格式发送的所有属性即可。 您将在操作中使用自己的逻辑填充它们:
public ActionResult GetSeries(string category)
{
// look up your category and series information
var model = new GetSeriesViewModel
{
categories = new[] { "category 1", "category 2" /* etc. */ }, // you can create this list from your code above
series = new[] { new SeriesViewModel { name="pa", data=new int[] { 1, 2, 3, 4, 5 } } }// etc.... again, you can create these objects in your code above */
};
return Json(model, JsonRequestBehavior.AllowGet)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.