I wanted to share a little trick I just found out for refreshes that I wanted to share with you guys, since you most likely will come across this if you haven’t already. Jason also asked me about it earlier and I actually needed to address it this afternoon.
I have a web application that a user starts off by selecting an event through a drop down. On submission of this selection, in order to not use some partial view that “un-hides” after selection, the cleanest way I thought of was to use the RedirectToAction method and have the View tied to that action take that value and do what it needs to do with it inside the view. Now, I thought that the Redirect method would allow you to pass a model, but alas it does not.
Because this is a Redirect (in HTTP land a 301 redirect), and the stateless nature of the MVC application, the next page loses any data you had from the previous form.
So what does one do? Use TempData of course. This is a generic object that you can fill with anything and then cast on the other end back to what it should be. Great you say right? Well here is the catch. Although TempData will temporarily persist using Session actually, once a get is made to the TempData object, the TempData is nulled out, and refresh will redirect you to the drop down page because you no longer have that data. Argggg.
Now, you can’t use ViewData, because it doesn’t persist pages on a redirect like that. Apparently, there is a Keep method in TempData that will make TempData keep its value for the refresh. The beauty here is that every time you refresh, if you put the keep call at the top, it will continue to do the same thing. Then when you go to another page, it removes it immediately.
Yes, I know this can most likely be done easily with Session or cache cookies, but I try to avoid doing to in MVC for several reasons:
1.) MVC is supposed to be stateless and if you start putting too much in the cache or session, you’ll end up with Web Forms ViewState.. trust me you don’t want that
2.) Session needs to be managed where TempData does things efficiently by its lonesome self.
3.) This was a scenario where it only needed to be in one page, not persistent throughout the application.