3

@Html.DropDownListFor需要一个 SelectListItem 列表。有没有办法在这里使用自定义对象而不是选择列表项并告诉下拉列表自定义对象的哪些属性用于值和文本?或者有没有一种简单的方法可以将我的客户对象转换为 SelectListItem?

我有一个状态对象: public string StatusCode {get;set;} public string StatusCodeDescription {get;set;}

所以现在我必须编写一个 for 循环来将我所有列表的状态转换为 SelectListItem ......这似乎需要一种更简单的方法......

4

1 回答 1

6

@Html.DropDownListFor requires a List of SelectListItem. Is there a way to use a custom object here instead of select list item and tell the drop down list which properties of the custom object to use for the value and text?

You could use the SelectList constructor taking 3 arguments: an IEnumerable<T> and 2 strings representing the names of the value and text properties of the custom type:

@Html.DropDownListFor(
    x => x.SelectedStatusCode, 
    new SelectList(
        Model.Satuses, 
        "StatusCode",  
        "StatusCodeDescription"
    )
)

In this example we assume that Model.Satuses is a property of type IEnumerable<StatusViewModel> where StatusViewModel contains at least 2 properties to bind the respectively the value and the text of the dropdown:

public class StatusViewModel
{
    public string StatusCode { get; set; } 
    public string StatusCodeDescription { get; set; }
    ...
}
于 2013-03-29T21:55:10.940 回答