我将 VS2012 RC 与 MVC4 一起使用,机器人用于所有意图和目的,让我们假装它是 MVC3。我想知道关于如何使用与父视图使用不同模型的表单来处理 PartialViews 的标准最佳实践是什么。
例如,这是一个显示所有可用角色的表格的视图,并且还有一个允许用户添加更多角色的表单。
主视图 - Roles.cshtml:
@model IEnumerable<RobotDog.Models.RoleModel>
<table>
@foreach(var role in Model) {
<tr>
<td class="roleRow">@role.Role</td>
</tr>
}
</table>
<div class="modal hide">
@Html.Partial("_AddRolePartial")
</div>
_AddRolePartial.cshtml
@model RobotDog.Models.RoleModel
@using(Html.BeginForm("AddRole","Admin", FormMethod.Post)) {
@Html.TextBoxFor(x => x.Role, new { @class = "input-xlarge", @placeholder = "Role"})
<input type="submit" value="Submit" class="btn btn-primary btn-large"/>
}
模型:
public class RoleModel {
[Required]
[DataType(DataType.Text)]
[Display(Name = "Role")]
public string Role { get; set; }
}
视图控制器:
public ActionResult Roles() {
var model = from r in System.Web.Security.Roles.GetAllRoles()
select new RoleModel {Role = r};
return View(model);
}
部分视图的控制器:
[HttpPost]
public ActionResult AddRole(RoleModel model) {
try {
System.Web.Security.Roles.CreateRole(model.Role);
RedirectToAction("Roles");
} catch(Exception) {
ModelState.AddModelError("", "Role creation unsuccessful.");
}
return ????; // not sure how to pass ModelState back to partialView
}
我考虑过创建一个持有的 ViewModel,RoleModel
但IEnumerable<RoleModel>
似乎会有一种更流线型的方式来完成我想要的,而不必每次我想使用这个 PartialView 时都创建一个 ViewModel。