ASP.NET MVC で最初のステップを踏んで、単純な (そして典型的な) コメント付きの記事ページを作成しようとしています。記事自体の下に、ユーザーが記事にコメントを投稿できるようにするフォームが必要です。
送信フォームの部分ビューを作成し、CommentController
次のメソッドを使用しました。
public ActionResult Add(int entryId);
[HttpPost]
public ActionResult Add(Comment comment);
次に、ビューの記事の下でHomeController
:
<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);
}
それとも、別のアプローチを取るべきでしょうか?