Search code examples
asp.net-mvcasp.net-mvc-3entity-frameworkactioncontroller

Object reference not set to an instance of an object error MVC3


I have a ajax post which give me the values from what the user have typed into my form.

And in my database I have two entites that are being used and I use model first. However Im getting "Object reference not set to an instance of an object" error when trying to do this:

goalCardQuestionAnswer.SelectedQuestion.Id = selectedQuestionViewModel.QuestionID;

This is my controller post:

    [HttpPost]
    public bool AnswerForm(SelectedQuestionViewModel selectedQuestionViewModel)
    {
        if (ModelState.IsValid)
        {
        var goalCardQuestionAnswer = new GoalCardQuestionAnswer();

        goalCardQuestionAnswer.SelectedQuestion.Id = selectedQuestionViewModel.QuestionID;
        goalCardQuestionAnswer.Comment = selectedQuestionViewModel.Comment;
        goalCardQuestionAnswer.Grade = selectedQuestionViewModel.Grade;

        answerNKIRepository.SaveQuestionAnswer(goalCardQuestionAnswer);
        answerNKIRepository.Save();

        }

My SelectedQuestionViewModel:

   public class SelectedQuestionViewModel
{

    public int? Grade { get; set; }
    public string Comment { get; set; }
    public string SelectedQuestionText { get; set; }
    public int QuestionID { get; set; }

}

My database model

enter image description here


Solution

  • You must initialize your SelectedQuestion property:

    var goalCardQuestionAnswer = new GoalCardQuestionAnswer();
    goalCardQuestionAnswer.SelectedQuestion = new SelectedQuestion();