我試圖設置一個小的演示,其中一篇文章有多個評論。文章詳細信息視圖應以局部視圖呈現註釋。 partialView本身包含另一個用於添加新評論的局部視圖。爲什麼PartialView不斷調用自己?
當我嘗試添加其他評論時,我收到一個InsufficientExecutionStackException
,因爲控制器中的操作不斷調用它自己。爲什麼會發生?
(如果有人有手頭的課程材料類似的例子應該是在模塊9中從MSFT的70-486課程;這就是我試圖建立。)
編輯:完整的代碼在github
編輯2: Github上的示例已修復。正如Stephen Muecke指出的那樣,事實上,GET
和POST
方法都使用相同的名稱導致循環引用。 在有更多人指出之前,DI和View Models缺失,並且重新渲染所有評論都是次優的:是的,我意識到並且沒有,那些事情什麼都不是,我想完成。這只是一個快速的骯髒演示。
控制器:
[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<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 })
_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>
}
順便說一句,如果訓練材料,指示您使用實體模型類作爲ViewModel或DTO,那麼我應該告訴你這是不好的做法 - 總是使用專用的ViewModel/DTO類型,而不是重新使用實體模型類型。 – Dai
我只是用一個簡單的'CommentsController :: Details'操作複製了一個新的空項目的視圖,我不能重現這個問題。你能否將你的整個項目放在一個Zip /檔案中? – Dai
爲什麼POST方法在視圖中已經有了它們的時候會返回所有註釋(而不僅僅是將新註釋添加到視圖中) –