利用ViewData生成JavaScript数组
这次用JSCharts做报表,发现对于生成报表参数很是恼火,它有两种参数:
一是Line:var myData = new Array([10, 20], [15, 10], [20, 30], [25, 10], [30, 5]);
二是Bar:var myData = new Array(['unit', 20], ['unit two', 10], ['unit three', 30], ['other unit', 10], ['last unit', 30]);
如何将Controller中获得的数据生成JavaScript的数组呢?
一种是toJson的方法:
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
var data=new Array();
$(document).ready(function(){
var content=<%=ViewData["Schedules"]==null?0:ViewData["Schedules"] %>;
if(content!=0)
{
$.each(content, function(i, item) {
data.push(new Array(item["ItemA"],item["ItemB"],item["ItemC"]));
});
}
});
参考:http://www.soaspx.com/dotnet/asp.net/DPattern/dpattern_20091104_1419.html
另一种是foreach ViewData,我选的这种:
public class Address
{
public string Line1 { get; set; }
public string City { get; set; }
}
// in your controller code
ViewData["Addresses"] = new List<Address>(new Address[] { new Address() { Line1="bla", City="somewhere"}, new Address() {Line1="foo", City="somewhereelse"}});
前台:
<script type="text/javascript">
var addresses = new Array(
<% for (int i = 0; i < ViewData["Addresses"].Count; i++) { %>
<%= i > 0 : "," : "" %>({line1:"<%= addr.Line1 %>", city:"<%= addr.City %>"})
<% } %>);
</script>
还可以这样:
var cityList = new Array();
function addCity(cityId, cityName) {
var city = new Object();
city.CityID = cityId;
city.CityName = cityName
cityList .push(city);
}
<% foreach (Something.DB.City item in ViewData["Cities"] as List<City>)
{ %>
addCity(item.Id, item.Name);
<% } %>
有几点需要注意,我的代码如下:
var callin = new Array();
function addReport( callin, callout) {
var data = new Array(callin, callout);
array.push(data);
}
'<%foreach(var item in ViewData["reports"] as List<CDRDayReport>){ %>'
addReport('<%=item.CallIn %>','<%=item.CallOut %>'); //string
//addReport(<%=item.CallIn %>,<%=item.CallOut %>); //number
'<%} %>'
PS:JSCharts的需要的参数,是数组嵌套数组。开始我一直没弄明白怎么生成这样的数据,其实很简单:
var array = new Array();
var data = new Array(10, 2);
var data2 = new Array(12, 3);
array.push(data);
array.push(data2);
唯一需要注意的是,如果只有1个data,JSCharts会报错,因为一个点生成不了line嘛,后来才想通。
作 者:doku
出 处:http://www.cnblogs.com/kulong995/
关于作者:喜欢编程,喜欢美食,专注于.NET项目开发。
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!