Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing object in Session

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");
        }
    }
like image 737
Arno 2501 Avatar asked Aug 09 '12 14:08

Arno 2501


People also ask

Can I store object in session?

Yes, You can save the class objects/instance in session and access at other pages.

How do you save an object in a session?

This is done so that the data can be stored in a file, a memory buffer or can be transferred over a network. session_start(); $object = new sample_object(); $_SESSION['sample'] = serialize($object); The session is started by using the 'session_start' function and a new object is created.

How do you store a value in a session?

The Session Storage basically consists of 4 main methods. setItem(key, value): This method is used to set the value into the Session Storage based on the key. getItem(key): This method is used to get the value that is stored into the Session Storage. It takes a key and returns the value.

What should not be stored in session?

Things like Database Data such as User Rows should not be stored in the session and you should create a separate cache mechanism to do this for you. Save this answer.


2 Answers

Storing the wizard:

Session["object"] = wiz;

Getting the wizard:

WizardProductVM wiz = (WizardProductVM)Session["object"];
like image 120
CalabiYau Avatar answered Oct 04 '22 09:10

CalabiYau


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)

like image 20
Shawn Avatar answered Oct 04 '22 09:10

Shawn