Reputation: 27703
I have the following scenario that may warrant storing data in a conroller member variable in order to share it between actions.
I have a search form and a button - when clicked, a table full of data returns according to the search form parameters. One action - all good and clean.
I am now asked to put an excel button so that the user can download the table in excel format. I don't want to run the db query again, since the data is already there, but since I am using a server side Excel component, I need the data to be available on the server in order to shove it into Excel.
My initial idea was to have an extra variable in my controller where the data can be stored. But I have never seen this being done in asp.net MVC. Is this an accepted pattern? My understanding was that each action is sort of isolated.
Upvotes: 3
Views: 8882
Reputation: 1854
I would suggest to use TempData, for example it's described here http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
Update: return file as done here Returning a file to View/Download in ASP.NET MVC
It's a normal practice to have a separate controller to return the file.
Upvotes: 1
Reputation: 34238
The MVC pattern encourages statelessness. This means if you want to keep data between actions it needs to get posted from the client (the server shouldn't maintain any state relating to a specific session). (so yes each action should be isolated, and shouldn't be reliant on any previous action, ie it shouldn't rely on setup from a previous request)
Take a read of scott Gu's blog on what MVC means here http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx
If you are having performance problems accessing data my recommendation is to use serverside caching of your data fetch. This should ideally be implemented in your data access or query layer in your application and shouldnt be strongly tied to a specific session
Upvotes: 2
Reputation: 8562
The controller is thrown away after each request. You get a new one everytime. If you want to store the data, the easiest would be to put it into session state.
Upvotes: 2