2

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.

shuniar
  • 2,592
  • 6
  • 31
  • 38

1 Answers1

4

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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks. What about if I have multiple dropdowns to set a couple properties, say five? Is this still a good implementation, or does this begin to clutter the model? – shuniar Sep 20 '11 at 14:39
  • @shuniar, still a very good implementation. Remember that the role of a view model class is to reflect on the requirements of a given view. So if you need to display 5 ddls in a view you will have 5 corresponding scalar properties on your view model to bind the selected values to and 5 collections to bind the options to. – Darin Dimitrov Sep 20 '11 at 14:42
  • Thanks for the clarification. I will continue to go with this implementation. – shuniar Sep 20 '11 at 14:44