我有一个partialView,它有一个<select>
,其中包含要注册的用户的可用角色列表。我是MVC的新手,我正在努力弄清楚如何绑定<select>
。
通常我会在ascx的Page_Load
上这样做,例如:
rolesSelect.DataSource = Roles.GetAllRoles().OrderBy(r => r);
rolesSelect.DataBind();
但是MVC就完全不同了。我的观点和部分观点看起来像这样:
Users.cshtml
@model IEnumerable<RobotDog.Models.UserModel>
<table>...</table>
<div id="addUser">
@Html.RenderPartial("_AddUser")
</div>
_AddUser.cshtml
@model RobotDog.Models.RegisterModel
@using(Html.BeginForm("AddUser","Admin", FormMethod.Post)) {
@Html.EditorFor(x => x.Email, new { @class = "input-xlarge", @placeholder = "Email"})
@Html.EditorFor(x => x.UserName, new { @class = "input-xlarge", @placeholder = "User Name"})
@Html.EditorFor(x => x.Password, new { @class = "input-xlarge", @placeholder = "Password"})
@Html.DropDownListFor(????) //not sure how to bind this?
}
我的问题是:
- 我需要将适当的集合从控制器传递到视图再传递到partialView吗?或者有更实用的可伸缩方法吗
- 有没有可能为partialView设置一个控制器,这样我就只需要担心将partialView添加到视图而不是视图的控制器
- 归根结底,将数据集合绑定到PartialView中的DropDownList的标准做法是什么
将Roles
集合添加到模型中,并根据需要构建选择列表。
@Html.DropDownListFor(x => x.Role,
Model.Roles.Select(role =>
new SelectListItem() { Text = role.Name, Value = role.Value }
)
)
将Roles
添加到模型的另一种选择是创建一个HTMLHelper方法。这是一种扩展方法,所以像这样添加:
namespace ExtensionMethods
{
public static class HtmlHelperExtensions
{
public static IEnumerable<SelectListItem> GetRoles(this HtmlHelper helper)
{
return new[] {
new SelectListItem() { Text="Role1" },
new SelectListItem() { Text="Role2" },
};
}
}
}
然后在Views
文件夹下的Web.Config
中注册命名空间:
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="ExtensionMethods"/>
</namespaces>
</pages>
</system.web.webPages.razor>
现在您可以创建下拉列表:
@Html.DropDownListFor(x => x.Role, Html.GetRoles())