Mar*_*rco 6 c# asp.net asp.net-mvc
我试图设置一个小型演示,其中一篇文章有多个评论.文章详细信息视图应该在局部视图中呈现注释.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);
}
Run Code Online (Sandbox Code Playgroud)
文章的Details.cshtml中的相关行:
@Html.Action("_GetCommentsForArticle", "Comments", new { articleId = Model.ArticleId})
Run Code Online (Sandbox Code Playgroud)
_GetCommentsForArticle:
@model IEnumerable<Mod9_Ajax.Models.Comment>
<div id="all-comments">
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Text)
</th>
</tr>
@foreach (var item in Model)
{
@* ... *@
}
</table>
</div>
@Html.Action("_CreateCommentForArticle", "Comments", new { articleId = ViewBag.ArticleId })
Run Code Online (Sandbox Code Playgroud)
_CreateCommentForArticle:
@model Mod9_Ajax.Models.Comment
@using (Ajax.BeginForm("_CreateCommentForArticle", "Comments", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "all-comments"
}))
{
@* ... *@
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Run Code Online (Sandbox Code Playgroud)
小智 2
为了解释发生的情况,您有一个表单可以发布到您的_CreateCommentForArticle()方法,然后该表单呈现您的_GetCommentsForArticle.cshtml部分内容,其中又包含@Html.Action("_CreateCommentForArticle", ...).
在最初的GET方法中Details()视图会被正确渲染,但是当你提交表单时,当前请求的页面_GetCommentsForArticle是一个[HttpPost]方法,所以@Html.Action()会寻找一个[HttpPost]方法(而不是[HttpGet]方法)。依次[HttpPost]渲染_GetCommentsForArticle.cshtml部分并再次调用_CreateCommentForArticle()渲染_GetCommentsForArticle.cshtml部分的 POST 方法,依此类推,直到内存耗尽并引发异常。
您可以通过更改 POST 方法的名称来解决此问题,例如
[HttpPost]
public PartialViewResult Create(Comment comment, int articleId)
Run Code Online (Sandbox Code Playgroud)
并修改表格以适应
@using (Ajax.BeginForm("Create", "Comments", new AjaxOptions { ...
Run Code Online (Sandbox Code Playgroud)