在Asp .Net MVC中创建一个下拉菜单可以通过以下步骤完成:
public class UserModel
{
// other properties
public List Roles { get; set; }
}
public class UserController : Controller
{
public ActionResult Create()
{
UserModel model = new UserModel();
model.Roles = GetRoles(); // 从数据库中获取角色列表
return View(model);
}
private List GetRoles()
{
// 从数据库中获取角色列表的代码
}
}
@model UserModel
@using (Html.BeginForm())
{
// other form fields
@Html.LabelFor(model => model.Roles, "Role")
@Html.DropDownListFor(model => model.Roles, new SelectList(Model.Roles), "Select a role", new { @class = "form-control" })
}
在上述代码中,@Html.DropDownListFor方法用于创建下拉菜单。第一个参数指定下拉菜单的属性,第二个参数是一个SelectList对象,用于指定下拉菜单的选项,第三个参数是一个提示文本,显示在下拉菜单的第一项,最后一个参数用于指定下拉菜单的CSS样式。
以上是一个简单的示例,你可以根据自己的需求进行修改和扩展。