且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将控制器数据加载到javascript数组中?

更新时间:2023-12-02 19:11:52

创建一个与要显示的属性匹配的类,即它将具有名为Label< string>的标签属性,a属性称为数据集,它是包含属性fillColour等的对象列表。



在控制器中,您可以创建此类的实例并从数据中填充它并传递给它对于视图,要么作为整个模型,要么作为模型的属性,如果您需要传递其他东西,那么您的模型将具有ChartData属性,该属性是您填充的图表数据的实例。



在视图中执行类似



Create a class that matches the properties you want to show, ie it will have a property called labels that is List<string>, a property called datasets that is a List of objects that contain properties fillColour etc.

In your controller you create an instance of this class and populate it from your data and pass it to the view, either as the whole model, or as a property of the model if you need to pass other things, so your model will have a "ChartData" property that is an instance of your populated chart data.

In the view do something like

var barChartData = @Json.Encode(Model.ChartData)





你可能需要;




you might need;

var barChartData = @Html.Raw(Json.Encode(Model.ChartData))





这将生成html,将barChartData js变量设置为应具有正确属性的json对象。查看页面源代码,看看你的输出与你需要的匹配程度,然后根据需要进行调整。



编辑:如果MVC3中没有Json.Ensode,那么使用任何东西支持将数据序列化为JSON,google为例。



That will generate html that will set the barChartData js variable to be a json object that should have the correct properties. View the page source to see how well your output matches what you need then tweak as appropriate.

if Json.Ensode isn't available in MVC3 then use whatever is supported to serialise the data to JSON, google for examples.


我建​​议使用名为HighCharts的图表构建JS库。这是一个很棒的工具,易于使用,有大量文档



可在互动中找到您网页的JavaScript图表| Highcharts [ ^ ]
May i suggest utilising chart building JS library called HighCharts. It's a great tool, easy to use with plenty of documentation

can be found at Interactive JavaScript charts for your webpage | Highcharts[^]