Storing object in Session

2019-04-28 12:58发布

问题:

I know this subject has been treated in numerous posts but I just cannot work it out.

Within an Controller Inside an ActionResult I would like to store an object in the Session and retrieve it in another ActionResult. Like that :

    public ActionResult Step1()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Step1(Step1VM step1)
    {
        if (ModelState.IsValid)
        {
            WizardProductVM wiz = new WizardProductVM();
            wiz.Step1 = step1;
            //Store the wizard in session
            // .....
            return View("Step2");
        }
        return View(step1);
    }

    [HttpPost]
    public ActionResult Step2(Step2VM step2)
    {
        if (ModelState.IsValid)
        {
            //Pull the wizard from the session
            // .....
            wiz.Step2 = step2;
            //Store the wizard in session again
            // .....
            return View("Step3");
        }
    }

回答1:

Storing the wizard:

Session["object"] = wiz;

Getting the wizard:

WizardProductVM wiz = (WizardProductVM)Session["object"];


回答2:

If you only need it on the very next action and you plan to store it again you can use TempData. TempData is basically the same as Session except that it is "removed" upon next access thus the need to store it again as you have indicated you are doing.

http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).aspx

If possible though, it may be better to determine a way to use posted parameters to pass in the necessary data rather than relying on session (tempdata or otherwise)