2012-06-22 82 views
0

我正在學習在父動作中嵌入子動作,並在從子動作提交表單時正確呈現整個頁面。MVC Parent Child操作頁面呈現?

ParentAction.cshtml --------------------------------------

@model Web1.Models.ParentActionModel 
@{ViewBag.Title = "ParentAction";} 
<h2>Parent Action</h2> 
@Html.ValidationSummary(true, "Please correct parent errors and try again.") 
@using (Html.BeginForm()) { 
    //parent forminput stuff 
    <input type="submit" value="Parent Button" /> 
} 
@Html.Action("ChildAction","Home") <!-- ChildAction is included here --> 

ChildAction.cshtml(包含在parent.cshtml)------------

@model Web1.Models.ChildActionModel 
@{ViewBag.Title = "ChildAction";} 
<h2>Child Action</h2>  
@Html.ValidationSummary(true, "Please correct child errors and try again.") 
@using (Html.BeginForm("ChildAction", "Home")) { 
    //child form input stuff 
    <input type="submit" value="Child Button" /> 
} 

HomeController.cs ---------------- -------

public ActionResult ParentAction() { 
    return View(); 
} 
[HttpPost] 
public ActionResult ParentAction(ParentActionModel pmodel) { 
    //do model update stuff 
    return View(pmodel); 
} 
[ChildActionOnly] 
public ActionResult ChildAction() { 
    return PartialView(); 
} 
[HttpPost] 
public ActionResult ChildAction(ChildActionModel cmodel) { 
    //do model update stuff 
    return PartialView(cmodel); // <---This is wrong, What's the correct way to do it? 
} 

現在,當我點擊「兒童按鈕」時,我只會看到c hild action(durrr!),我該如何解決它以生成完整頁面父級+子級視圖?這似乎很容易,但我堅持了幾個小時。

回答

2

所以,如果我刪除了[ChildActionOnly]在HttpPost詳細方法, 當我點擊提交,只返回Details.cshtml partialView, 不與Master.cshtml,這不是我想要的,都不是。

那是因爲你不應該在這種情況下返回PartialView,而是一個完整的視圖:

[HttpPost] 
public virtual ActionResult Details(DetailsModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     return View(model); 
    } 

    return RedirectToAction("Success"); 
} 

您可能還只需要有條件地呈現Details行動,以避免無限循環:

@if (!IsPost) 
{ 
    @Html.Action("Details", "Home") 
} 

很顯然,如果你想保留當你調用這個POST動作時你所處的原始上下文,你將不得不使用AJAX,然後用AJAX調用這個POST動作,並且只替換c或DOM的對應部分。

+0

當你回答時,我正在重寫我的問題。因爲我想也許這沒有道理。對於那個很抱歉。請檢查我的問題? – Tom

+0

我的答案依然存在。從POST操作返回一個完整的視圖,而不是一個PartialView。 –

+0

你爲什麼需要這樣的事情?您如何期望能夠區分標準瀏覽器POST請求和任何人都可以僞造的POST請求?唯一的方法是使用身份驗證,並且具有有效身份驗證cookie的用戶可以自由地直接向您的服務器僞造POST請求,而無需使用Web瀏覽器。 –