Reputation: 2622
I am developing an application in MVC3 which has dropdown lists on quite a few pages to populate selections for specific objects. My question is does it make more sense to contain the collections for the dropdown list in my ViewModel or call a service to populate the dropdowns.
For example, does it make more sense to have this:
public class MyViewModel
{
public int SelectedFooId { get; set; }
public IEnumerable<Foo> Foos { get; set; }
}
@Html.DropDownListFor(model => model.SelectedFooId, new SelectList(Model.Foos, "Id", "Name", "-- Select Foo --"))
Or is there a better way to implement this by removing the Foos
collection from the view model and populating it with ajax through json or something? If I call a service, can you provide an example of how this would be done? I am still relatively new to MVC and am trying to do everything by best practice as I don't want to get into any bad habbits.
Upvotes: 2
Views: 794
Reputation: 1038930
That's a very good way to render drop down lists in an ASP.NET MVC application. You define a view model containing 2 properties : a scalar property to bind the selected value to and a collection to bind the options to. Then you have the controller action populate this view model and pass to the view and inside the view you use the DropDownListFor
helper.
Using AJAX to populate values of a dropdown could be useful when doing some dynamic binding. For example you could do this with cascading drop down lists where the selection on the first ddl would condition the values of the second. Here's an example of how this could be implemented.
Upvotes: 4