0

我正在尝试将一个对象从一个控制器传递到另一个控制器,但它的行为方式并没有我想要的那样。在下文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不包含任何元素,尽管调用者显然传递了一个包含四个元素的集合。我想我误解了它是如何工作的——像这样在控制器之间通信对象的正确方法是什么?

4

1 回答 1

2

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

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

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

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

有关更多信息,请参阅此问题及其答案

于 2013-04-15T19:43:35.117 回答