Need simple example of how to populate javascript array from Viewdata list

此生再无相见时 提交于 2019-12-05 03:04:24

问题


There may be a simpler way of doing this and I am all ears if there is. My situation is I have a dropdownlist on a form which I successfully populate with text and values. I also need to have additional related string values from the same table row in the db table available on the client so when the user selects from the dropdown this related data gets populated in a textbox on the form. There are only 4 records I'm dealing with so storing on the client is no big deal. I thought about passing this data via ViewData as a list and loading into a javascript array. When the user selects from the dropdown - I would determine the selected index and get the related data I need from the array. I am already using the value of the dropdown item for other required data so I need a way to get this related data without making a return trip to the server. If I am on the right track could someone post a simple example of populating a js array with sting values returned as a List in the ViewData.

Thanks,

Mike


回答1:


var myArray = [
<% foreach (string item in ViewData["list"] as List<string>) { %>
"<%= item %>",
<% } %>
];

Having a comma at the end will reportedly break in IE, so I would suggest a view extension helper method to make the code easier to manage:

<%= Html.JavaScriptArray(ViewData["list"] as List<string>, "myArray") %>

Put this helper method somewhere in you 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"); // Not the prettiest but it works...
    }
    sb.append("];");
    return sb.toString();
}

Technically the extension method can go anywhere, you'll just need to include the namespace in you .aspx file. Practically its best to keep them in logically separated classes, such as MyApp.Mvc.Extensions.JavaScriptExtensions, MyApp.Mvc.Extensions.LinkExtensions




回答2:


how about...

<%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["list"]) %>


来源:https://stackoverflow.com/questions/662277/need-simple-example-of-how-to-populate-javascript-array-from-viewdata-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!