I have a select element in my razor view and I want to populate its options using code in an external Javascript file. The option data consists of a Dictionary which is available to my controller class. How can I access that dictionary in the JS file, via my view model?
Asked
Active
Viewed 122 times
0
-
1Are you using the razor views? – Vishnu Aug 27 '19 at 16:18
1 Answers
0
If all you are doing is populating a drop down menu, like most people, then you don't have to worry about that. You can simply build the options right from C# in your Razor view.
Populating a razor dropdownlist from a List<object> in MVC
@Html.LabelFor(m => m.SelectedUserRoleId)
@Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)
I that's not your use case, then you can populate your JS array in a slightly different manner.
Razor MVC Populating Javascript array with Model Array
var myArray = [];
@foreach (var d in Model.data)
{
@:myArray.push("@d"); // for basic data
// or
@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2"); // for objects
}

computercarguy
- 2,173
- 1
- 13
- 27