[英]How to handle PartialView with different model than parent View
我将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。
我认为您在问如何将RoleModel传递给添加的RoleModel模态弹出窗口。 由于您正在创建新角色,因此我假设您需要一个空模型。 您可以像下面这样传递它:
<div class="modal hide">
@Html.Partial("_AddRolePartial", new RoleModel())
</div>
或者只是使用控制器的支持GET方法执行@Html.RenderAction("AddRole")
以支持填充项。
public ActionResult AddRole() {
var model = new RoleModel();
//populate with any items needed for the Add Role Model View
return View(model);
}
将表单发布更改为ajax表单发布,目标更新部分ID为div
,您将添加到父视图(有效地围绕Roles.cshtml)。
添加一个新的动作public ActionResult _Roles()
,它将return PartialView("Roles", model)
接下来,在“发布操作”中,最后Return RedirectToAction(...Roles Partial Action ...)
,并在try
删除RedirectToAction(“ Roles”)。
我个人不喜欢将Partial View与表单一起使用,因为Partial Views无法正确呈现子模型(即,它们未考虑模型的层次结构)。
这就是为什么存在Display和EditorTemplates的原因。 它们非常适合呈现特定的数据类型。
但是,在您的情况下,由于视图本身没有任何形式,并且最终结果只是父模型集合中的单个项,因此部分视图实际上是一种更好的方法,因为您可以通过与视图使用的模型不同。
正如其他人指出的那样,您可以轻松地将一个空模型作为第二个参数传递给局部模型。 我不喜欢在视图中更新新对象,但是看起来那里没有太多选择,因为其他选择非常混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.