简体   繁体   English

如何使用与父视图不同的模型处理PartialView

[英]How to handle PartialView with different model than parent View

I'm using VS2012 RC with MVC4, bot for all intents and purposes let's pretend it's MVC3. 我将VS2012 RC与MVC4结合使用,出于所有目的和目的,该机器人让我们假装为MVC3。 I would like to know what the standard best practice(s) is on how to handle PartialViews with a form that uses a different model than the parent View. 我想知道标准的最佳做法是如何处理使用与父视图使用不同模型的表单的PartialViews。

For example, here is a view that displays a table of all the available Roles and also has a form that allows the user to add more roles. 例如,这里的视图显示所有可用角色的表,并且具有允许用户添加更多角色的表单。

Main View - Roles.cshtml: 主视图-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 _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"/>
}

Model: 模型:

public class RoleModel {
    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Role")]
    public string Role { get; set; }
}

Controller for View: 视图控制器:

public ActionResult Roles() {
    var model = from r in System.Web.Security.Roles.GetAllRoles()
                select new RoleModel {Role = r};
    return View(model);
}

Controller for PartialView: 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
}

I thought about creating a ViewModel that held RoleModel and IEnumerable<RoleModel> but it seems like there would be a more stream lined way to accomplish what I wanted without having to create a ViewModel everytime I wanted to use this PartialView. 我曾考虑过创建一个可以RoleModelIEnumerable<RoleModel>的ViewModel,但似乎有一种更简单的方法可以完成我想要的事情,而不必每次我都想使用此PartialView时都创建ViewModel。

I think you are asking how to pass a RoleModel to the add RoleModel modal popup. 我认为您在问如何将RoleModel传递给添加的RoleModel模态弹出窗口。 Since you are creating a new Role, I am assuming you are needing an empty model. 由于您正在创建新角色,因此我假设您需要一个空模型。 You can either pass it in like below: 您可以像下面这样传递它:

<div class="modal hide">
    @Html.Partial("_AddRolePartial", new RoleModel())
</div>

Or just do a @Html.RenderAction("AddRole") with the supporing GET method of the controller to support populating the item. 或者只是使用控制器的支持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);
}

How about the form post is changed to an ajax form post with a target update partial id being the div which you will add to the parent view (effectively surrounding Roles.cshtml). 将表单发布更改为ajax表单发布,目标更新部分ID为div ,您将添加到父视图(有效地围绕Roles.cshtml)。

Add a new action public ActionResult _Roles() which will return PartialView("Roles", model) 添加一个新的动作public ActionResult _Roles() ,它将return PartialView("Roles", model)

Next, in the Post Action, Return RedirectToAction(...Roles Partial Action ...) at the end and remove RedirectToAction("Roles") in the try . 接下来,在“发布操作”中,最后Return RedirectToAction(...Roles Partial Action ...) ,并在try删除RedirectToAction(“ Roles”)。

I personally don't like using Partial views with forms, because Partial Views do not render submodels correctly (ie, they don't take into account the hierarchy of the model). 我个人不喜欢将Partial View与表单一起使用,因为Partial Views无法正确呈现子模型(即,它们未考虑模型的层次结构)。

This is why Display and EditorTemplates exist. 这就是为什么存在Display和EditorTemplates的原因。 They work well for rendering specific data types. 它们非常适合呈现特定的数据类型。

However, in your case, since your view doesn't have any forms of its own, and the end result is just a single item of the collection of your parent model, then a Partial View is actually a better approach simply because you CAN pass a different model to it than the views uses. 但是,在您的情况下,由于视图本身没有任何形式,并且最终结果只是父模型集合中的单个项,因此部分视图实际上是一种更好的方法,因为您可以通过与视图使用的模型不同。

As others have pointed out, you can easily pass an empty model to the partial as the second parameter. 正如其他人指出的那样,您可以轻松地将一个空模型作为第二个参数传递给局部模型。 I don't like newing up new objects in the view, but it doesn't look like there's a lot of choice there, as the alternatives would be pretty messy. 我不喜欢在视图中更新新对象,但是看起来那里没有太多选择,因为其他选择非常混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM