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?

1
  • 1
    Are you using the razor views? Commented Aug 27, 2019 at 16:18

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.