ASP.NET MVC 3 Razor:初始化一个 JavaScript 数组 [英] ASP.NET MVC 3 Razor : Initialize a JavaScript array
问题描述
在 ASP.NET MVC 3 中使用 Razor 初始化 JS 数组的首选方法是什么,我的模型/视图模型中有一个值?
What would be the prefered way to initialize a JS array in ASP.NET MVC 3 with Razor with a value I have in my model/view model ?
例如初始化表示日期的字符串数组:
For example to initialize an array of strings representing dates :
<script type="text/javascript">
var activeDates = ["7-21-2011", "7-22-2011"];
</script>
与
public class MyViewModel
{
public DateTime[] ActiveDates { get; set; }
}
推荐答案
我不太明白 JS 和 ASP.NET MVC 3 Razor 之间的关系.无论在服务器上使用哪种技术生成页面,Javascript 都在客户端运行.所以在 javascript 上,一个数组就是一个数组.
I don't quite understand the relation between JS and ASP.NET MVC 3 Razor. Javascript runs on the client side no matter which technology has been used on the server to generate the page. So on javascript an array is an array.
在 javascript 中定义对象数组有几种可能性
There are a couple of possibilities to define arrays of objects in javascript
var activeDates = [ '7-21-2011', '7-22-2011' ];
或:
var activeDates = new Array();
activeArrays.push('7-21-2011');
activeArrays.push('7-22-2011');
或尚未:
var activeDates = new Array();
activeArrays[0] = '7-21-2011';
activeArrays[1] = '7-22-2011';
最后所有这些都代表同一个数组.但它是一个字符串的数组,而不是日期.
At th end all those represent the same array. But it is an array of strings, not dates.
如果你想要一个日期数组,你可以这样做:
If you wanted to have an array of dates, here's what you could do:
var activeDates = [
new Date(2011, 6, 21, 0, 0, 0, 0),
new Date(2011, 6, 22, 0, 0, 0, 0)
];
现在我能看到的与您对 ASP.NET MVC 的问题的唯一关系是您的视图模型上可能有一些数组:
Now the only relation I can see with your question to ASP.NET MVC is that you probably have some array on your view model:
public class MyViewModel
{
public DateTime[] ActiveDates { get; set; }
}
您想在 javascript 数组中序列化和操作.在这种情况下,语法如下:
that you wanted to serialize and manipulate in a javascript array. In this case here's the syntax:
@model MyViewModel
<script type="text/javascript">
var activeDates = @Html.Raw(Json.Encode(Model.ActiveDates));
</script>
现在,由于 DateTime 字段在 .NET 中以 JSON 序列化的方式,您将在生成的 HTML 中得到以下内容:
Now because of the way DateTime fields are JSON serialized in .NET you will end up with the following in the generated HTML:
var activeDates = ["\/Date(1309471200000)\/","\/Date(1311199200000)\/"];
如果你想把这个字符串数组转换成一个实际的javascript日期数组:
and if you wanted to convert this array of strings into an array of actual javascript dates:
var dates = $.map(activeDates, function(date, index) {
date = date.replace('/Date(', '').replace(')/', '');
return new Date(parseInt(date));
});
这篇关于ASP.NET MVC 3 Razor:初始化一个 JavaScript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!