Maintaining ViewData Between RenderAction Calls

I provide a generic login form using Html.RenderAction on every page of my site.

If the user enters their details in the text box and clicks Submit, they POST to the controller that handles the login.

If they make a mistake, such as entering an invalid email address, it will populate the ModelState with an error message and then redirect back to whatever page they were on before.

The problem is that the RenderAction happens as a separate request, I am losing the ViewModel.

Even when I put it in TempData, it gets lost as TempData is cleared from every single request.

Is there a way to preserve data between successive calls to Html.RenderAction?

If not, any suggestions on how I can hack this? (Should be putting data into Session?)

+2


source to share


2 answers


Here's what I've done so far. (This is probably not the most ideal solution.)

I created a "PreserveViewDataAttribute" to which I applied any action for which I want to keep the ViewData in the session.

In my BaseController, I tried the Redirect method with my own method, which does the following.

  • Gets a reference to the Action method that called it (a bit of reflection here)

  • Checks if this method has 'PreserveViewDataAttribute' defined on it

  • If so, copies the current ViewData to a session variable. (The variable label is the same as the name of the current activity, with '_ViewData' appended to the end.)

  • Calls the underlying redirect method anyway.



Then I created a property in BaseController named "PreservedViewData" that returns a ViewData in the session relative to the current activity. (Or returns null if not found).

Thus, to keep the ViewData for as long as I want, I only need to decorate my action with "PreserveViewDataAttribute" and then call "PreservedViewData" whenever I need it.

Let me know if you want the source code.

0


source


You may like this Post-Redirect-Get Kazi Rashid approach.



http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg

-1


source







All Articles