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

后端 未结 5 2067
小蘑菇
小蘑菇 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<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

    0 讨论(0)
  • 2020-12-09 19:58

    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.

    0 讨论(0)
  • 2020-12-09 20:04

    Your best bet is to create a SelectList in your Controller - use my extension method here: http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc

    Pop that into ViewData using the same key as your property name: ViewData["statusid"]=MySelectList

    Then just use Html.DropDownFor(x=>x.StatusID) and you're all set.

    0 讨论(0)
  • 2020-12-09 20:04

    I find it more intuitive to work with a sequence of SelectListItems (rather than a SelectList).

    For example, this would create an IEnumerable<SelectListItem> from a sequence of customer objects that you can pass to the Html.DropDownListFor(...) helper. The 'Selected' property will optionally set the default item in the dropdown list.

    var customers = ... // Get Customers
    var items = customers.Select(c => new SelectListItem
                                 {
                                     Selected = (c.Id == selectedCustomerId),
                                     Text = c.Email,
                                     Value = c.Id.ToString()
                                 }); 
    
    0 讨论(0)
  • 2020-12-09 20:07

    (You know this already!)

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

    Yes, add it when you build the SelectList. (If you build the list using LINQ, Union might come in handy.)

    Yes do do, and yes you are.

    0 讨论(0)
提交回复
热议问题