类型' System.NullReferenceException'的例外情况: 你调用的对象是空的

时间:2015-07-27 23:15:04

标签: c# asp.net-mvc

所以我真的很困惑。我有一些代码:

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
    }

但由于某种原因,我的代码返回错误:An exception of type 'System.NullReferenceException' : Object reference not set to an instance of an object.查看调试器时,它会显示question = null,但我设置了question的所有属性并实例化它,所以我真的很困惑这里出了什么问题......任何指导都会非常感激。

2 个答案:

答案 0 :(得分:4)

您应该直接致电generateViewForSurveyQuestion()以返回视图:

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,您的SurveyQuestion对象无法正确表示。

答案 1 :(得分:0)

我认为您可以使用如下的TempData。

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