Razor MVC 使用模型数组填充 Javascript 数组 [英] Razor MVC Populating Javascript array with Model Array
问题描述
我正在尝试使用我的模型中的数组加载 JavaScript 数组.在我看来,这应该是可能的.
I'm trying to load a JavaScript array with an array from my model. Its seems to me that this should be possible.
以下方法均无效.
无法创建 JavaScript 循环并通过带有 JavaScript 变量的模型数组递增
Cannot create a JavaScript loop and increment through Model Array with JavaScript variable
for(var j=0; j<255; j++)
{
jsArray = (@(Model.data[j])));
}
无法创建 Razor 循环,JavaScript 超出范围
Cannot create a Razor loop, JavaScript is out of scope
@foreach(var d in Model.data)
{
jsArray = d;
}
我可以让它工作
var jsdata = @Html.Raw(Json.Encode(Model.data));
但我不知道为什么我必须使用 JSON.
But I don't know why I should have to use JSON.
此外,目前我将其限制为 255 个字节.将来它可能会遇到很多 MB.
Also while at the moment I'm restricting this to 255 bytes. In the future it could run into many MBs.
推荐答案
这是可以的,你只需要遍历razor集合
This is possible, you just need to loop through the razor collection
<script type="text/javascript">
var myArray = [];
@foreach (var d in Model.data)
{
@:myArray.push("@d");
}
alert(myArray);
</script>
希望能帮到你
这篇关于Razor MVC 使用模型数组填充 Javascript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!