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");
}
}
Yes, You can save the class objects/instance in session and access at other pages.
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.
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.
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.
Storing the wizard:
Session["object"] = wiz;
Getting the wizard:
WizardProductVM wiz = (WizardProductVM)Session["object"];
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With