2013-07-27 180 views
1

第一步與ASP.NET MVC,我想創建一個簡單的(和典型的)文章與評論頁面:在文章本身應該有一個表格,使用戶可以發表評論文章。重定向錯誤

我創建了一個局部視圖爲與下面的方法提交表單和CommentController:在HomeController視圖

public ActionResult Add(int entryId); 

[HttpPost] 
public ActionResult Add(Comment comment); 

然後,在相應的文章:

<div class="add-comment"> 
    @{ Html.RenderAction("Add", "Comment", new { entryId = Model.EntryId }); } 
</div> 

形式呈現正確和添加程序實際工作(註釋保存到數據庫),但重定向迴文章InvalidOperationException被拋出,Html.RenderAction(上面顯示的那個)在調試器中高亮顯示:

System.InvalidOperationException:子操作不允許執行重定向操作。

爲什麼會發生?

下面是CommentController方法的代碼:

public ActionResult Add(int entryId) 
{ 
    var comment = new Comment { EntryId = entryId }; 
    return PartialView(comment); 
} 

[HttpPost] 
public ActionResult Add(Comment comment) 
{ 
    if (ModelState.IsValid) 
    { 
     comment.Date = DateTime.Now; 
     var entry = db.Entries.FirstOrDefault(e => e.EntryId == comment.EntryId); 
     if (entry != null) 
     { 
      entry.Comments.Add(comment); 
      db.SaveChanges(); 
      return RedirectToAction("Show", "Home", new { id = entry.EntryId }); 
     } 
    } 

    return PartialView(comment); 
} 

或者,也許我應該甚至採取不同勢的方法嗎?

+0

這個答案可能有一個完美。我看到我在某些時候投了票,所以它至少幫助了我:) http://stackoverflow.com/questions/2056421/why-are-redirect-results-not-allowed-in-child-actions-in -asp-net-mvc-2 –

+1

從數據庫中獲取評論的動作方法在哪裏? –

+0

沒有。傳遞給視圖的模型類(動作顯示)具有作爲導航屬性的註釋集合,因此顯示它們不是問題。 – Clueless

回答

0

另添加操作

+1

它並沒有真正改變任何東西。但感謝您的答案。 – Clueless

0

你應該/可以使用RenderPartial代替RenderAction添加HttpGet

Html.RenderPartial("YourPartialView", new Comment { EntryId = Model.EntryId }); 

那裏看來是沒有必要用你的操作方法,如果你正在做的是實例化一個你已經擁有這個ID的模型。