MVC:在 javascript 中迭代 Viewbag 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5830549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:05:54  来源:igfitidea点击:

MVC: Iterating a Viewbag array in javascript

javascriptasp.net-mvcarraysrazorviewbag

提问by Esa

The goal is to get the data from the ViewBag.Arrayto a Javascript array. The data is calculated in the controller so I cannot fetch it straight from the database. I need the data to draw a chart with jqplot. Code:

目标是将数据从ViewBag.Array到 Javascript 数组。数据是在控制器中计算的,所以我无法直接从数据库中获取它。我需要使用 jqplot 绘制图表的数据。代码:

for(i = 0; i < @ViewBag.Array.Length; i++)
{
    jScriptArray[i] = @ViewBag.Array[i];
}

The problem is "'i' does not exist in the current context" in the @ViewBag.Array[i]but has no problems in the jScriptArray[i]. Any help is appreciated.

问题是“'i' 在当前上下文中不存在”,@ViewBag.Array[i]但在jScriptArray[i]. 任何帮助表示赞赏。

回答by Darin Dimitrov

You may try the following:

您可以尝试以下操作:

var array = @Html.Raw(Json.Encode(@ViewBag.Array));
for(var i = 0; i < array.length; i++) {
    jScriptArray[i] = array[i];
}

回答by Dmitry Bosikov

<script>
var jScriptArray=[];
@{
    for(i = 0; i < ViewBag.Array.Length; i++){
      <text>jScriptArray[@i] = "@ViewBag.Array[@i]";</text>
      i++;
    }
  }
</script>

You will end up with something like this in html file:

你最终会在 html 文件中得到这样的东西:

jScriptArray[0] = "ArrayValue0";
jScriptArray[1] = "ArrayValue1";
jScriptArray[2] = "ArrayValue2";

回答by LeArm

var [email protected](JsonConvert.SerializeObject(ViewBag.Array));

you can make use of JsonConvert.SerializeObjectHope this Helps.

你可以使用 JsonConvert.SerializeObject希望这有帮助。

回答by alexl

The best way to achieve your goal is to create a JSON controller that returns the data into a JSON array.

实现目标的最佳方法是创建一个 JSON 控制器,将数据返回到 JSON 数组中。

From your javascript you can request the data and then process it.

您可以从您的 javascript 请求数据,然后对其进行处理。

Hope this helps

希望这可以帮助