Search code examples
asp.net-mvcmodel-view-controllerpostbackpersist

How to re-use model data on post back with MVC


I'm passing structured data to my MVC page when it loads initially. After the user submits a contact form, I want to re-use the same data (I just "leave" the same page up) so I don't have to hit the database again. I declared a variable global to the controller to store the model data, but it's null at the end of the post back, so it looks like I can't re-use it there.

Seems like this would be a typical scenario. How do I handle it?


Solution

  • If you are wanting to reuse viewmodel or other retrieved data that is not going to be part of the postback, you can either

    a) Output it in hidden fields so that it is posted back to your action (meh) or

    b) Store the object(s) in Session so that it will be available to any other controllers/actions in your application. If you are worried about memory, you could delete that session variable after you reuse it if you are not going to need to use it again.

    On your initial page load, check if the session variable exists, if it does, you are good - else populate it.

    Oh and why the global variable thing isn't working -> a controller is new'd up for each request (assuming using the default controller factory) and as such any global variables in the controller will be reset on each request.