这里有点奇怪。我有一个博客,它是另一个“涉足 MVC”项目,它将突出我们新 Intranet 的好处。我有一个典型的博客文章页面,其中包含文章、评论和一个表单,用于提交您对给定文章的评论。
我有一个字符串类型的主视图(“Post”),其中包含文章内容,然后是两个 Html.RenderAction 方法;一个获取评论,一个通过表单添加评论。
我的问题是,当发表评论时,我的 GetComments 方法在 AddComment 之前被调用,因此当刷新页面时,尽管新评论已添加到数据库中,但它是不可见的。快速 F5 确认了这一点。我知道 GetComments 被首先调用是因为它首先在视图中声明,但我不确定如何告诉视图在获取之前进行添加。
这是我的代码:
控制器:
public ActionResult AddComment()
{
return PartialView("AddComment");
}
[HttpPost]
public ActionResult AddComment(Comment comment)
{
comment.DateSubmitted = DateTime.Now;
db.Comments.Add(comment);
db.SaveChanges();
return PartialView(comment);
}
public ActionResult GetComments(int articleid)
{
var comments = db.Comments.Where(c => c.ArticleID == articleid).ToList();
return PartialView(comments);
}
发布视图
@model IntranetBlog.Models.Article
@{
ViewBag.Title = "Post";
}
<div class="row">
<div class="span12">
<h3>@Html.DisplayFor(modelItem => Model.Title)</h3>
<small>by Ruth Barlow on @Html.DisplayFor(modelItem => Model.DateCreated)</small>
@if (Model.Image != null)
{
<p>
<img src="@Url.Action("GetImage", "Home", new { articleID = Model.ArticleID })" alt="" width="150" height="150" />
</p>
}
<div>
@Html.DisplayFor(modelItem => Model.Body)
</div>
<small>Posted under @Html.DisplayFor(modelItem => Model.Category.Name)</small>
</div>
<div class="span12">
@{
Html.RenderAction("GetComments", "Home", new { articleID = Model.ArticleID });
}
</div>
<div class="span12">
@{
Html.RenderAction("AddComment", "Home", new { articleID = Model.ArticleID });
}
</div>
</div>
GetComments 部分:
@model IEnumerable<IntranetBlog.Models.Comment>
@if (Model.Any())
{
<h3>What you're saying</h3>
foreach (var item in Model)
{
<div>
Comment: @Html.DisplayFor(modelItem => item.Body)
</div>
<div>
Submitted by: @Html.DisplayFor(modelItem => item.SubmittedBy)
on @Html.DisplayFor(modelItem => item.DateSubmitted)
</div>
<hr />
}
}
else
{
<p>There are no comments for this post. Why not add one?</p>
}
添加评论部分
@model IntranetBlog.Models.Comment
@using (Html.BeginForm())
{
<h3>Why not leave us a comment?</h3>
@Html.ValidationSummary()
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Body, 20, 20, null)
@Html.ValidationMessageFor(model => model.Body)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.SubmittedBy)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.SubmittedBy)
@Html.ValidationMessageFor(model => model.SubmittedBy)
</div>
<p>
<input type="submit" value="Add comment" id="AddComment" class="btn btn- primary" />
</p>
</fieldset>
}
希望这是有道理的。提前致谢。