我在强类型视图中有来自Entity Framework的自动生成的DropDownList:
<div class="editor-field">
@Html.DropDownList("User_FK", String.Empty)
@Html.ValidationMessageFor(model => model.User_FK)
</div>
以下是行动代码:
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加载的人员的姓名。如何单独自定义选择列表选项?
答案 0 :(得分:2)
@Html.DropDownList
有另一个重载,即:
public static MvcHtmlString DropDownList(
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList
)
因此,您指定一个name
字符串,然后以您想要的方式生成IEnumerable<SelectListItem>
。
所以,(当然,我假设这里有一些类型 - MyUserType
,MyActiveDirectoryRepository
)
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)