0

I am trying to pass an object from one controller to another controller, but it is not behaving in the way that I would like it to. In the following ApplicantMainController, I am instantiating an object called ApplicationQuestions (which contains a List<ApplicationQuestion> object as one of its members) and then attempting to pass it via the RedirectToAction method call:

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 });
    }
}

When I redirect to the controller, it appears to make it:

private ApplicationQuestions m_questions;

// more code ...

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

However, though the reference is now bound to the parameter passed to the Apply method, the debugger tells me that the reference to the collection questions does not contain any elements, though clearly the caller passed a collection with four elements. I think I am misunderstanding how this works -- what is the proper way to communicate objects between controllers like this?

dtg
  • 1,803
  • 4
  • 30
  • 44

1 Answers1

2

One option is to use TempData to hold the object during the redirect.

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

Then grab the object out of TempData in the other action:

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

See this question and its answers for more information.

Community
  • 1
  • 1
Jason Berkan
  • 8,734
  • 7
  • 29
  • 39