0
我想輸出博客帖子中的所有評論。我已成功輸入數據庫中的所有數據,並可輸出帖子。但是我無法輸出評論。無法輸出帖子中的所有評論
我的帖子模型如下:
public class Post
{
[Key]
public int PostId { get; set; }
public string Title { get; set; }
public DateTime CreatedDate{get;set;}
public DateTime UpdateDate { get; set; }
public string Body { get; set; }
public ICollection<Comment> Comments { get; set;}
}
我的評論模型如下:
public int CommentId { get; set; }
public int PostId { get; set; }
[ForeignKey("PostId")]
public virtual Post Post{get; set;}
public string CommentCreateDate { get; set; }
public string CommentUpdateDate { get; set; }
public string CommeterName { get; set; }
public string EmailAddress { get; set; }
public string CommentText { get; set; }
public bool Approved { get; set; }
我的操作如下:
[HttpPost]
public ActionResult CreateComment(int ?id, CommentViewModel model)
{
Post post = GetPost(id);
var comment = new Comment();
comment.Post = post;
comment.CommentCreateDate = DateTime.Now.ToString();
comment.CommeterName = model.Name;
comment.EmailAddress = model.Email;
comment.CommentText = model.Text;
db.Comments.Add(comment);
db.SaveChanges();
m_commentList.Add(m_comment);
ViewData["Comment"] = comment;
ViewBag.Comment = comment;
TempData["Comment"] = comment;
return RedirectToAction("Index");
}
我的索引視圖被如下:
@using Blog.Models
@{
ViewBag.Title = "Index";
var viewDataComment = ViewData["Comment"] as Comment;
var tempDataComment = TempData["Comment"] as Comment;
bool isPreviousLinkVisible = ViewBag.IsPreviousLinkVisible ?? false;
bool isNextLinkVisible = ViewBag.IsNextLinkVisible ?? false;
bool isAdmin = ViewBag.IsAdmin ?? false;
}
@foreach (Post post in Model)
{
<div class="newsResult">
<div class="title">@Html.DisplayFor(modelItem => post.Title)</div>
<div class="updated"> <b>Created:</b> @Html.DisplayFor(modelItem => post.CreatedDate) </div>
<div class="updated"> <b>Updated:</b> @Html.DisplayFor(modelItem => post.UpdateDate)</div>
<div class="data"> <b></b> @Html.DisplayFor(modelItem => post.Body)</div>
@*<div class="data"> <b></b> @Html.DisplayFor(x => tempDataComment.CommentText)</div>*@
@foreach (Comment comment in post.Comments.OrderBy(x => x.CommentCreateDate)) //Offending line
{
<div class="comment">
<div class="commentName">
@if (!string.IsNullOrWhiteSpace(comment.EmailAddress))
{
<a href="mailto: @comment.EmailAddress;">@comment.CommeterName</a>
}
else
{
@comment.CommeterName;
}
</div>
said:
<div class="commentBody">@Html.Raw(Html.Encode(comment.CommentText).Replace("\n", "<br/>"))</div>
<div class="commentTime">at @comment.CommentCreateDate.ToString() on @comment.CommentCreateDate.ToString()</div>
</div>
}
上面的帖子顯示沒有問題。但是,當我試圖訪問它給了我一個異常的評論(出錯行是第二的foreach的開始):
System.ArgumentNullException: Value cannot be null
我確實知道該數據已被創建幷包括註釋這是否則可用於var tempDataComment
。
這是怎麼發生的?任何人都可以幫忙嗎?
預先感謝您!
這是發生在後或得到?你的帖子只是返回索引? – Peru
@Peru它發生在帖子中。在上面的視圖的職位控制器的索引視圖。我想列出在該視圖中的所有評論。 – bluetxxth
檢查您傳遞給控制器的型號是否有價值。我猜這是作爲NULL – Peru