MVC3 Customizing DropdownList items in strongly typed view
I have an auto generated DropDownList from Entity Framework in a strongly typed view:
<div class="editor-field">
@Html.DropDownList("User_FK", String.Empty)
@Html.ValidationMessageFor(model => model.User_FK)
</div>
Here is the action code:
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();
}
I ne开发者_JAVA技巧ed this list to display the names of people loaded from Active Directory. How do I customize the select list options seperately?
@Html.DropDownList
has another overload, namely:
public static MvcHtmlString DropDownList(
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList
)
So, you specify a name
string and then an IEnumerable<SelectListItem>
generated any way you want.
So, (of course, I'm assuming some types here--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
});
}
Pass the list to your view via View Model pattern ViewBag
public ActionResult Create()
{
// populate list as above
ViewBag.User_FK = new SelectList(users, "ID", "ADName");
return View();
}
Then, after passing it to your view (preferably, via view model not ViewBag)
@Html.DropDownList("NameOfDropDown", ViewBag.User_FK)
精彩评论