我是 MVC 的新手,所以请多多包涵。:-)
我有一个强类型的“故事”视图。此视图(故事)可以有评论。
我为我的 Comments 控制器“ListStoryComments”和“CreateStoryComment”创建了两个视图(不是部分视图),它们的功能与它们的名称所暗示的一样。这些视图使用 RenderAction 包含在 Story View 中,例如:
<!-- List comments -->
<h2>All Comments</h2>
<% Html.RenderAction("ListStoryComments", "Comments", new { id = Model.Story.Id }); %>
<!-- Create new comment -->
<% Html.RenderAction("CreateStoryComment", "Comments", new { id = Model.Story.Id }); %>
(我传入 Story id 以列出相关评论)。
所有工作都如我所愿,除了当我使用表单发布新评论时,它返回当前(父)视图,但评论表单字段仍显示我输入的最后内容,并且 ListStoryComments 视图未更新为展示新的故事。
基本上,页面是从缓存中加载的,就好像我按下了浏览器的后退按钮一样。如果我按 f5,它将尝试重新发布表单。如果我手动重新加载页面(在浏览器的地址栏中重新输入 URL),然后按 f5,我将看到我的新内容和空表单字段,这是我想要的结果。
为了完整起见,我的 CreateStoryComment 操作如下所示:
[HttpPost]
public ActionResult CreateStoryComment([Bind(Exclude = "Id, Timestamp, ByUserId, ForUserId")]Comment commentToCreate)
{
try
{
commentToCreate.ByUserId = userGuid;
commentToCreate.ForUserId = userGuid;
commentToCreate.StoryId = 2; // hard-coded for testing
_repository.CreateComment(commentToCreate);
return View();
}
catch
{
return View();
}
}