【发布时间】:2012-09-06 06:19:09
【问题描述】:
我将 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);
}
PartialView 的控制器:
[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
}
我曾想过创建一个包含 RoleModel 和 IEnumerable<RoleModel> 的 ViewModel,但似乎有一种更流线型的方式来完成我想要的事情,而不必每次我想使用这个 PartialView 时都创建一个 ViewModel。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 partial-views