0

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?

user2882061
  • 363
  • 2
  • 9

1 Answers1

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