Best way of implementing DropDownList in ASP.NET MVC 2?

12,730

Solution 1

Answering in parts:

  1. The best way IMHO is to pass the list in the ViewModel like this:

    public SelectList Colors
    {
        get
        {
            // Getting a list of Colors from the database for example...
            List<Color> colors = GetColors().ToList();
    
            // Returning a SelectList to be used on the View side
            return new SelectList(colors, "Value", "Name");
        }
    }
    
  2. To get a blank or default option like ( -- Pick a color -- ), you can do this on the view side:

    @Html.DropDownListFor(m => m.Color, Model.Colors, "-- Pick a color --")
    
  3. You'll have to fetch/populate the list again if it's part of the ViewModel.


Take a look at the following blog post. It can give you some tips:

Drop-down Lists and ASP.NET MVC

Solution 2

You could do something like:

<%= Html.DropDownListFor((x => x.ListItems), Model.ListItems, "")%>

or

<%= Html.DropDownList("ListItems", Model.ListItems, "")%>

The last param 'optionLabel' makes a blank list item

In this case, you can see ListItems is a property of the model.

I have made the view strongly typed to the model also.

Share:
12,730
Rohit Sharma
Author by

Rohit Sharma

Always out numbered, but never out matched!

Updated on June 03, 2022

Comments

  • Rohit Sharma
    Rohit Sharma almost 2 years

    I am trying to understand the best way of implementing a DropDownList in ASP.NET MVC 2 using the DropDownListFor helper. This is a multi-part question.

    First, what is the best way to pass the list data to the view?

    1. Pass the list in your model with a SelectList property that contains the data
    2. Pass the list in via ViewData

    How do I get a blank value in the DropDownList? Should I build it into the SelectList when I am creating it or is there some other means to tell the helper to auto create an empty value?

    Lastly, if for some reason there is a server side error and I need to redisplay the screen with the DropDownList, do I need to fetch the list values again to pass into the view model? This data is not maintained between posts (at least not when I pass it via my view model) so I was going to just fetch it again (it's cached). Am I going about this correctly?