MVC3在强类型视图中自定义DropdownList项

时间:2011-06-10 12:34:30

标签: entity-framework asp.net-mvc-3

我在强类型视图中有来自Entity Framework的自动生成的DropDownList:

 <div class="editor-field">
    @Html.DropDownList("User_FK", String.Empty)
    @Html.ValidationMessageFor(model => model.User_FK)
</div>

Auto Generated drop down list

以下是行动代码:

public ActionResult Create()
{
    ViewBag.SystemMaster_FK = new SelectList(db.SystemMasters, "System_PK", "Name");
    ViewBag.User_FK = new SelectList(db.Users, "User_PK", "NetworkLogin");
    return View();
} 

我需要此列表来显示从Active Directory加载的人员的姓名。如何单独自定义选择列表选项?

1 个答案:

答案 0 :(得分:2)

@Html.DropDownList有另一个重载,即:

public static MvcHtmlString DropDownList(
    this HtmlHelper htmlHelper,
    string name,
    IEnumerable<SelectListItem> selectList
)

因此,您指定一个name字符串,然后以您想要的方式生成IEnumerable<SelectListItem>

所以,(当然,我假设这里有一些类型 - MyUserTypeMyActiveDirectoryRepository

List<MyUserType> users = new List<MyUserType>();

foreach(var user in MyActiveDirectoryRepository.GetUsers())
{
    users.Add(new MyUserType()
    {
        ADName = user.Username,
        ID = user.ID // or SAM token, or something similar
    });
}

通过查看模型模式 ViewBag

将列表传递给您的视图
public ActionResult Create()
{
    // populate list as above
    ViewBag.User_FK = new SelectList(users, "ID", "ADName");
    return View();
}

然后,在将其传递给您的视图后(最好是通过视图模型 ViewBag)

@Html.DropDownList("NameOfDropDown", ViewBag.User_FK)