2

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."

1 Answer 1

2

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);
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

i was about to answer the same:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.