我尝试使用C#在ASP.NET MVC3中创建一个小博客应用程序。
我有一个BlogEntry类和评论类。
public class BlogEntry {
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public List<Comment> Comments { get; set; }
public void addComment(Comment comment)
{
Comments.Add(comment);
}
}
我想在特定博客帖子的现有评论列表中添加评论。我的控制器具有以下代码来添加注释。
[HttpPost]
public ActionResult Comment(CommentViewModel commentViewModel)
{
if (ModelState.IsValid)
{
//Create New Comment
Comment comment = new Comment();
//Map New Comment to ViewModel
comment.Title = commentViewModel.Title;
comment.Message = commentViewModel.Message;
comment.TimeStamp = DateTime.UtcNow;
//Save newComment
CommentDB.Comment.Add(comment);
CommentDB.SaveChanges();
//Get Entry by Id
BlogEntry blogEntry = BlogDB.BlogEntry.Find(commentViewModel.BlogEntryId);
// Add comment to Entry
blogEntry.addComment(comment); // ERROR DISPLAYED HERE
UpdateModel(blogEntry);
BlogDB.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View(commentViewModel);
}
}
当我尝试添加注释时,我收到以下错误:“对象引用未设置为对象的实例。”
答案 0 :(得分:2)
似乎您的评论列表未实例化。尝试这样的事情:
public class BlogEntry
{
public BlogEntry()
{
this.Comments = new List<Comment>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public List<Comment> Comments { get; set; }
public void addComment(Comment comment)
{
Comments.Add(comment);
}
}