System.NullReferenceException':对象引用不设置为对象的实例

本文关键字:设置 对象 实例 对象引用 NullReferenceException System | 更新日期: 2023-09-27 18:04:54

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

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的所有属性并实例化它,所以我真的很困惑这里出了什么问题.....如有任何指导,我将不胜感激。

System.NullReferenceException':对象引用不设置为对象的实例

您应该直接调用generateViewForSurveyQuestion()来返回视图:

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

您正在调用的RedirectToAction()的过载需要路由参数,您的SurveyQuestion对象不能正确表示。

我认为你可以像下面这样使用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......
    }