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

后端 未结 5 2072
小蘑菇
小蘑菇 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 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 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()
                                 }); 
    

提交回复
热议问题