perennial_
perennial_

Reputation: 1846

An exception of type 'System.NullReferenceException' : Object reference not set to an instance of an object

So I am really confused. I have some code:

public ActionResult submitSurveyQuestion(SurveyQuestion model) 
    {
        SurveyQuestion nextQuestion = new SurveyQuestion();
        nextQuestion = submitSurveyQuestionAndGetNextQuestionFromQuestion(model);
        return RedirectToAction("generateViewForSurveyQuestion", new { question = nextQuestion });
    }

public SurveyQuestion submitSurveyQuestionAndGetNextQuestionFromQuestion(SurveyQuestion currentQuestion)
    {
        SurveyQuestion surveyQuestion = new SurveyQuestion();
        surveyQuestion.Question = "question";
        //...etc, this just sets all the question properties
        return surveyQuestion;
    }
public ActionResult generateViewForSurveyQuestion(SurveyQuestion question)
    {
        //ERROR BELOW THIS LINE
        return View("SurveyQuestionType" + question.QuestionType, question);
        //ERROR ABOVE THIS LINE
    }

But for some reason, my code returns the error:An exception of type 'System.NullReferenceException' : Object reference not set to an instance of an object. When looking through the debugger, it says that question = null, but I set all the properties of question and instantiate it, so I am really confused as to what's going wrong here.....any guidance would be greatly appreciated.

Upvotes: 0

Views: 515

Answers (2)

Raj Karri
Raj Karri

Reputation: 551

I think you can use TempData as below.

public ActionResult submitSurveyQuestion(SurveyQuestion model) 
    {
        SurveyQuestion nextQuestion = new SurveyQuestion();
        nextQuestion = submitSurveyQuestionAndGetNextQuestionFromQuestion(model);
      TempData["question"] = nextQuestion;
        return RedirectToAction("generateViewForSurveyQuestion");
    }

public SurveyQuestion submitSurveyQuestionAndGetNextQuestionFromQuestion(SurveyQuestion currentQuestion)
    {
        SurveyQuestion surveyQuestion = new SurveyQuestion();
        surveyQuestion.Question = "question";
        //...etc, this just sets all the question properties
        return surveyQuestion;
    }
public ActionResult generateViewForSurveyQuestion()
    {
        // TempDate[question] available here......
    }

Upvotes: 0

Peter Gluck
Peter Gluck

Reputation: 8236

You should call generateViewForSurveyQuestion() directly to return the view:

public ActionResult submitSurveyQuestion(SurveyQuestion model) {
  SurveyQuestion nextQuestion = new SurveyQuestion();
  nextQuestion = submitSurveyQuestionAndGetNextQuestionFromQuestion(model);
  return generateViewForSurveyQuestion(nextQuestion);
}

The overload of RedirectToAction() which you are invoking requires route parameters, which your SurveyQuestion object cannot properly represent.

Upvotes: 4

Related Questions