为什么PartialView会自行调用?
我试图设置一个小型演示,其中一篇文章有多个评论。 文章详细信息视图应该在局部视图中呈现注释。 partialView本身包含另一个用于添加新注释的局部视图。
当我尝试添加另一个注释时,我收到InsufficientExecutionStackException
,因为控制器中的操作一直在调用自身。 为什么会这样?
(如果有人掌握了课程材料。类似的例子应该是来自Msft的70-486课程的模块9;这就是我想要建立的。)
编辑:完整代码在github上
Edit2: Github上的示例已修复。 正如Stephen Muecke所指出的那样,事实上, GET
和POST
方法都有相同的名称,导致循环引用。 在更多人指出之前,缺少DI和View模型,并且重新呈现所有注释都是次优的:是的我知道,不,那些事情都没有,我想完成。 这只是一个快速的脏演示。
控制器:
[ChildActionOnly] public PartialViewResult _GetCommentsForArticle(int articleId) { ViewBag.ArticleId = articleId; var comments = db.Comments.Where(x => x.Article.ArticleId == articleId).ToList(); return PartialView("_GetCommentsForArticle", comments); } public PartialViewResult _CreateCommentForArticle(int articleId) { ViewBag.ArticleId = articleId; return PartialView("_CreateCommentForArticle"); } [HttpPost] public PartialViewResult _CreateCommentForArticle(Comment comment, int articleId) { ViewBag.ArticleId = articleId; comment.Created = DateTime.Now; if (ModelState.IsValid) { db.Comments.Add(comment); db.SaveChanges(); } var comments = db.Comments.Where(x => x.Article.ArticleId == articleId).ToList(); return PartialView("_GetCommentsForArticle", comments); }
文章的Details.cshtml中的相关行:
@Html.Action("_GetCommentsForArticle", "Comments", new { articleId = Model.ArticleId})
_GetCommentsForArticle:
@model IEnumerable @Html.DisplayNameFor(model => model.Text) @foreach (var item in Model) { @* ... *@ }
@Html.Action("_CreateCommentForArticle", "Comments", new { articleId = ViewBag.ArticleId })
_CreateCommentForArticle:
@model Mod9_Ajax.Models.Comment @using (Ajax.BeginForm("_CreateCommentForArticle", "Comments", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "all-comments" })) { @* ... *@