我有一个可以包含评论对象的博客对象。
目前,博客包含博客信息以及呈现评论列表和添加新评论的表单的部分内容。此评论表单发布到Save
我的Comment
控制器中的操作,然后重定向回控制器的Show
操作Blog
。下面的代码是动作动作。
//the id of the blog this comment is for
int blogId;
bool parsed = Int32.TryParse(Request.Form["blogId"].ToString(), out blogId);
//get the blog
BlogService blogService = new BlogService(unitOfWork);
Blog blog = new Blog();
if (parsed)
{
blog = blogService.GetBlogArticle(blogId);
}
//setup up our comment
CommentService service = new CommentService(unitOfWork);
Comment comment = model;
comment.Blog = blog;
//set the comment date
comment.PostedDate = DateTime.Now;
bool actionSucceeded = true;
string errorMessage = "Something went wrong. Please try your request again.";
try
{
service.Add(comment);
unitOfWork.Save();
}
catch
{
actionSucceeded = false;
}
if (actionSucceeded)
{
TempData["ActionMessage"] = "Comment successfully added. Comments need approval before being posted.";
return RedirectToAction("show", "blog", new { id = comment.Blog.Id });
}
else
{
ModelState.AddModelError(string.Empty, errorMessage);
}
return RedirectToAction("show", "blog", new { id = comment.Blog.Id });
我的评论视图模型是这样设置的。
public class CommentListModel
{
public IEnumerable<Comment> Comments { get; set; }
public string ActionMessage { get; set; }
}
我的博客视图模型是这样设置的。
public class BlogModel : ResultsModel<Blog>
{
public Blog Blog { get; set; }
public string ActionMessage { get; set; }
public BlogModel() : base()
{
this.ItemsPerPageOptions = new KeyValuePair<int, string>[]
{
new KeyValuePair<int, string>(15, "Items Per Page: 15"),
new KeyValuePair<int, string>(20, "Items Per Page: 20"),
new KeyValuePair<int, string>(25, "Items Per Page: 25"),
new KeyValuePair<int, string>(30, "Items Per Page: 30"),
new KeyValuePair<int, string>(40, "Items Per Page: 40"),
new KeyValuePair<int, string>(50, "Items Per Page: 50")
};
}
}
以及处理这个的视图部分。
@if (TempData["ActionMessage"] != null)
{
<div class="validation-summary-success" style="font-size: 2.1em; color: gray; background-color: #90EE90; padding: 10px; margin:2px;">
<ul>
<li>@TempData["ActionMessage"]</li>
</ul>
</div>
<script type="text/javascript">
$(".validation-summary-success").delay(3000).fadeOut("slow").slideUp("slow");
</script>
}
<div class="Head">
<h5>@Model.Blog.Title</h5>
<label>By: @Model.Blog.Admin.Name <span>| @Model.Blog.PostingDate.ToShortDateString()</span></label>
</div>
<article class="mContent">
<p>@Model.Blog.Body</p>
</article>
<div id="commentContainer">
@Html.Partial("_BlogComments", @Model.Blog.Comments, new ViewDataDictionary { {"blogId", @Model.Blog.Id} })
</div>
如您所见,我使用TempDataDictionary
来显示“已保存”消息。但是,据我了解,这违背了拥有强类型视图的目的。
当我在操作中保存此评论时,如果我重定向回控制器的操作,如果此操作当前接受记录 ID Save
,我该如何设置属性?我会设置博客或评论对象的属性吗?ActionMessage
Show
Blog
ActionMessage