难以将对象从一个控制器传递到另一个控制器

时间:2013-04-15 19:39:53

标签: asp.net-mvc-4

我正在尝试将一个对象从一个控制器传递到另一个控制器,但它的行为并不像我希望的那样。在下面的ApplicantMainController中,我实例化一个名为ApplicationQuestions的对象(其中包含一个List<ApplicationQuestion>对象作为其成员之一),然后尝试通过RedirectToAction方法传递它拨打:

public ActionResult FormAction(FormCollection collection)
{
    if (collection["cmdSearch"] != null)
    {
        // more code above...

        ApplicationQuestions questions = new ApplicationQuestions();

        MultipleChoiceQuestion q1 = new MultipleChoiceQuestion("Can you lift 50 pounds?");
        MultipleChoiceQuestion q2 = new MultipleChoiceQuestion("Are you at least 18 years of age?");
        MultipleChoiceQuestion q3 = new MultipleChoiceQuestion("Are you legally able to work in the US?");
        MultipleChoiceQuestion q4 = new MultipleChoiceQuestion("Have you ever been convicted of a felony?");

        q1.AddPossibleAnswer(1, new Answer("Yes", true));
        q1.AddPossibleAnswer(2, new Answer("No", false));
        q2.AddPossibleAnswer(1, new Answer("Yes", true));
        q2.AddPossibleAnswer(2, new Answer("No", false));
        q3.AddPossibleAnswer(1, new Answer("Yes", true));
        q3.AddPossibleAnswer(2, new Answer("No", false));
        q4.AddPossibleAnswer(1, new Answer("Yes", false));
        q4.AddPossibleAnswer(2, new Answer("No", true));

        questions.AddQuestion(q1);
        questions.AddQuestion(q2);
        questions.AddQuestion(q3);
        questions.AddQuestion(q4);

        // not sure how to pass the object here??
        return RedirectToAction("Apply", "ApplicantApply", new { model = questions });
    }
}

当我重定向到控制器时,它似乎成功:

private ApplicationQuestions m_questions;

// more code ...

public ActionResult Apply(ApplicationQuestions questions)
{
    m_questions = questions;
    return RedirectToAction("NextQuestion", "ApplicantApply");
}

但是,虽然引用现在绑定到传递给Apply方法的参数,但调试器告诉我对集合questions的引用不包含任何元素,但显然调用者已通过一个有四个元素的集合。我想我误解了它是如何工作的 - 在这样的控制器之间传递对象的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

一种选择是在重定向期间使用TempData来保存对象。

TempData["MyCoolData"] = questions;
return RedirectToAction("Apply", "ApplicantApply");

然后在另一个动作中从TempData中抓取对象:

m_questions = (ApplicationQuestions)TempData["MyCoolData"];

有关详细信息,请参阅this question and its answers