var myArray = [
<% foreach (string item in ViewData["list"] as List<string>) { %>
"<%= item %>",
<% } %>
];
After the decimal point at the end, it is reported that there will be a break in IE, so I would suggest a helper method to expand the view to simplify code management:
<%= Html.JavaScriptArray(ViewData["list"] as List<string>, "myArray") %>
Put this helper method somewhere in your solution:
public static string JavaScriptArray(this HtmlHelper htmlHelper, IList<string> values, string varName) {
StringBuilder sb = new StringBuilder("var ");
sb.append(varName);
sb.append(" = [");
for (int i = 0; i < values.Count; i++) {
sb.append("'");
sb.append(values[i]);
sb.append("'");
sb.append(i == values.Count - 1 ? "\n" : ",\n");
}
sb.append("];");
return sb.toString();
}
Technically, the extension method can go anywhere, you just need to include the namespace in the .aspx file. It’s practically best to keep them in logically separated classes, such as MyApp.Mvc.Extensions.JavaScriptExtensions,MyApp.Mvc.Extensions.LinkExtensions
roryf source
share