How do I pass data across ActionResults in MVC 3?

2019-04-16 02:47发布

问题:

I have a series of pages that an end user must fill out (check boxes) and when they are finished with each page I attempt to create a List of the check boxes they selected. At the end of the series of pages, I would like to show them everything that they have selected in a confirmation page. I have noticed that between requests the information in the List<> I create on each page is not available to the final confirmation page. I've tried a few different solutions (private globals) to no avail. How would I pass data across ActionResults to accomplish displaying all the selected data on the confirmation page? Thanks.

One potential solution. Others?

回答1:

The web is stateless, meaning you have to store things if you want to keep them around for later use. That's true for any web framework. You'll need to store each page's results somewhere.

Options for building a wizard:

  • Store all of the selected answers in session and keep building it up from page to page. The final confirmation would get the results from session.
  • Store them in a database.
  • Store results in in a cookie.
  • Store them in HTML5 local storage
  • Carry them through on each page with hidden fields. Page 2 would have Page 1's answers in hidden fields, etc.


回答2:

You need to save a state between the requests. You can do this with:

  1. Query string parameters
  2. Session state
  3. Hidden fields
  4. Db (if you wanna persist the intermediate choices after each request)
  5. Local storage
  6. Cookies

Anything else?

I'd guess, as RyanW points out, that storing them in session state is the usual way to do it. You could however fetch all steps in one request, do some fancy JS / store the intermediary results locally and make a final post when the questionnaire is complete.



回答3:

You should look here

Initialy you need to keep necessary variables in hidden fields and send Model completely through all requests.