我需要一些帮助来解决如何在MVC3中使用Html.DropDownListFor,因为文档很糟糕,而且我找不到我需要的答案。
我有以下型号
public class Users
{
public virtual User_Roles RoleID {get; set;}
public virtual string UserName{get; set;}
... more stuff
}
public class User_Roles
{
public virtual Int32 RoleID {get; set;}
public virtual string Role {get; set;}
}
我的页面(create_user.cshtml)如下所示:
@model Users
... stuff
@Html.LabelFor(m => m.RoleID)
@Html.DropDownListFor(m => m.RoleID, Model.RoleID.Role, Model.RoleID.RoleID)
不断抛出错误"'System.Web.Mvc.HtmlHelper<Users>' does not contain a definition for 'DropDownListFor'"
有人可以向我解释如何从数据库中提取角色名称和ID列表,因为这显然不是这样做的吗?
答案 0 :(得分:2)
您需要使用SelectList
传递下拉项。
确保从控制器中检索ViewBag.Roles
中的角色。
@Html.DropDownListFor(m => m.RoleId, new SelectList(ViewBag.Roles as System.Collections.IEnumerable, "Id", "Name"), "")