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

后端 未结 5 2066
小蘑菇
小蘑菇 2020-12-09 19:40

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 ques

5条回答
  •  温柔的废话
    2020-12-09 19:51

    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 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

提交回复
热议问题