C# 控制器中的 ASP NET MVC 数组到客户端数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17581982/
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
ASP NET MVC array in controller to client side array
提问by coredump
My question is how ( if possible ) from an array like string[] a;that I pass it to the
view through the ViewBag, how can I obtain a javascript array of strings.
我的问题是如何(如果可能)从这样的数组string[] a;中通过 将它传递给视图ViewBag,如何获取字符串的 javascript 数组。
I want to use this because I get a set of data from the DB and I want in the view to make chart and for that I need a javascript array.
我想使用它是因为我从数据库中获取了一组数据,我想在视图中制作图表,为此我需要一个 javascript 数组。
采纳答案by McGarnagle
It's easy to "render" an array to a Javascript object, using string.Joinor similar:
使用string.Join或类似的方法将数组“渲染”到 Javascript 对象很容易:
@{
ViewBag.a = new int[] { 1, 2, 3 };
ViewBag.b = new string[] { "a", "b", };
}
<script type='text/javascript'>
// number array
var a = [ @(string.Join(", ", (int[])ViewBag.a)) ];
console.log(a); // [1, 2, 3]
// string array -- use Html.Raw
var b = [@Html.Raw("'" + string.Join("', '", (string[])ViewBag.b) + "'")];
console.log(b);
</script>
回答by atbebtg
Controller
控制器
public ActionResult Index()
{
int[] myArray = new int[] { 1, 3, 5, 7, 9 };
ViewBag.myArray = myArray;
return View();
}
View
看法
@{
ViewBag.Title = "Index";
var myArray = (int[])ViewBag.myArray;
var myjsstring = "";
for(int i =0;i<myArray.Length;i++)
{
myjsstring += "mycars[" + i.ToString() + "] = " + myArray[i] + ";";
}
}
<script type="text/javascript">
var mycars = new Array();
@myjsstring
</script>
回答by user3442612
Perhaps:
也许:
@{
ViewBag.foo = new string[] { "a", "b", "c" };
}
var newFoo = @Html.Raw(Json.Encode(@ViewBag.foo));

![C# 从 DataRow [] 集合中选择一个 DataRow](/res/img/loading.gif)