为什么PartialView会自行调用?

我试图设置一个小型演示,其中一篇文章有​​多个评论。 文章详细信息视图应该在局部视图中呈现注释。 partialView本身包含另一个用于添加新注释的局部视图。

当我尝试添加另一个注释时,我收到InsufficientExecutionStackException ,因为控制器中的操作一直在调用自身。 为什么会这样?

(如果有人掌握了课程材料。类似的例子应该是来自Msft的70-486课程的模块9;这就是我想要建立的。)

编辑:完整代码在github上

Edit2: Github上的示例已修复。 正如Stephen Muecke所指出的那样,事实上, GETPOST方法都有相同的名称,导致循环引用。 在更多人指出之前,缺少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 
@foreach (var item in Model) { @* ... *@ }
@Html.DisplayNameFor(model => model.Text)
@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" })) { @* ... *@ 
}

为了解释发生了什么,你有一个表格发布给你_CreateCommentForArticle()方法,然后呈现你的_GetCommentsForArticle.cshtml部分,其中包括@Html.Action("_CreateCommentForArticle", ...)

Details()的初始GET方法中,视图将被正确呈现,但是当您提交表单时, _GetCommentsForArticle页面的当前请求是[HttpPost]方法,因此@Html.Action()将查找[HttpPost]方法(不是[HttpGet]方法)。 [HttpPost]反过来呈现_GetCommentsForArticle.cshtml部分并再次调用_CreateCommentForArticle() POST方法,该方法将_GetCommentsForArticle.cshtml部分呈现,等等,直到内存不足并抛出exception为止。

例如,您可以通过更改POST方法的名称来解决此问题

 [HttpPost] public PartialViewResult Create(Comment comment, int articleId) 

并修改表格以适应

 @using (Ajax.BeginForm("Create", "Comments", new AjaxOptions { ...