Help Adding item to existing Object List (ASP.NET MVC C#)
I'm try to make a little blog application in ASP.NET MVC3 with C#.
I have a BlogEntry Class and Comment Class.
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);
}
}
I want to add a Comment to the existing Comment List for a particular Blog post. My Controller has the following code to add a 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);
}
}
When I try to add a comment I get the following error: "Object reference not set to an instance of an object."
It seems like your Comments list isn't instantiated. Try something like this:
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);
}
}
精彩评论