Mike Marks
Mike Marks

Reputation: 10139

How can I persist data between two completely different views in ASP.NET MVC 4?

I've been trying to figure out a solution for quite some time, to no avail. What I have is a form. I'm using ASP.NET MVC4 with jQuery Mobile. The user is first directed to the following screen:

enter image description here

Here, they choose a capsule and click Submit. The capsule they choose has a primary key value that I want to persist to the next page.

Once they click Submit, they will be taken to:

enter image description here

Here, they'll fill out the form and click "Create". The fillers list that you see on this screenshot is based on the capsule selected on the previous screen. So, depending on the capsule selected, the filler list above can vary. How can I retain the Capsule's primary key value that was selected on the previous screen and persist it to the next screen (a completely different view)? I understand I cannot use ViewBag because ViewBag is only in the scope of a single View. Essentially, what I want is the data on the form above, as well as the primary key of the capsule selected in the previous view.

Upvotes: 2

Views: 2899

Answers (3)

Tbonechk27
Tbonechk27

Reputation: 150

You can make the variable holding the value static

Upvotes: 0

Judo
Judo

Reputation: 5247

You will need to post the value back to the server from View1 and then pass that back to View2 via a Controller action method: Below is a code snippet that show was happens on the server :

//Serve the view when the URL is requested
    public ActionResult ViewAllItems()
    { 
        return View();
    }


//Handle the posted form from the ViewAllItems page
 [HttpPost]
    public ActionResult ViewAllItems(int selectedItemId)
    { 
        RedirectToAction("ViewItemDetail", new { id = selectedItemId });
    }

    public ViewResult ViewItemDetail(int id)
    { 
       var item = repo.GetItem(id);
       return View(item);
    }

Here the method with the Controller Action method ViewAllItems receives the posted value and redirects to the ViewItemDetail method which then loads the item data and passes it to the view. The view will hence be passed the id (along with the full item).

This is the general MVC pattern where the values are passed up to controller action methods and then relayed back to views.

Upvotes: 3

Trey Gramann
Trey Gramann

Reputation: 2004

Consider this psuedo code but in essence the controllers could look like this...

[HttpPost]
public ActionResult FormOnePost(ModelFromFormOne modelFromFormOne)
{
    var model = new ModelForFormTwo();
    model.Filters = IList<Filter> from database? query using id
    model.MoreStuff etc.
    return View("ViewTwoWithSecondForm", model);
}

This keeps from exposing your primary key in the path.

Upvotes: 0

Related Questions