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

There may be an easier way to do this, and I am all ears, if any. My situation: I have a drop-down list in the form that I successfully fill in 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 drop-down list, this related data is filled in the text box in the form. There are only 4 entries that I deal with, so storing on the client is not a big deal. I was thinking about passing this data through ViewData as a list and loading into a javascript array. When the user selects from the drop-down list, I would define the selected index and get the necessary data from the array. I already use the value of the dropdown element for other necessary data,so I need a way to get this related data without making a trip back to the server. If I'm on the right track, someone can post a simple example of populating a js array with sting values ​​returned as List in ViewData.

Thanks,

Mike

+3
source share
2 answers
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"); // Not the prettiest but it works...
    }
    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

+7
source

What about...

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

Source: https://habr.com/ru/post/1705026/


All Articles