簡體   English   中英

如何使用與父視圖不同的模型處理PartialView

[英]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
}

我曾考慮過創建一個可以RoleModelIEnumerable<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM