[SOLVED] Maintaining data between views in mvc4

Issue

I would like to know how I can flow data between multiple actions in MVC4.

For example, user is landing at one page (non-authenticated), fills in some data then goes to 2nd view, fills in another set of data, and then on submit, the code checks if the user is authenticated then proceeds further, otherwise go to login / register view, authenticate and redirect to 3rd step.

Now, I want to know how I can keep the data for that user while they are authenticating, should I put the data in session object and once the user is done with authentication retrieve the data? I’m not sure how to do it in MVC the right way, since it’s a bit different compared to web forms.

Solution

What you could do is to create a TempData key in your initial controller and when the value is returned, its value would be what the user has input.

In your controller action:

 [HttpPost]
 public ActionResult LandingPage(LandingPageViewModel model)
 {
    TempData["Model"] = model;
    return RedirectToAction("OtherDataPage");
 }

So on your landing page, when the user sends input, you store it in TempData and then redirect the user to the other page to fill information.

In the other action, you can use TempData to set object values from the user’s previous input.

 public ActionResult OtherDataPage()
 {
    LandingPageViewModel model = new LandingPageViewModel();
    model = TempData["Model"];
    return View();
 }

Something like that should persist the user input

Answered By – biddano

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *