Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect After Post in ASP.NET MVC

Tags:

asp.net-mvc

I am using the Redirect After Post pattern in my ASP.NET MVC application. I have the following scenario:

  1. User goes to /controller/index where he is asked to fill a form.
  2. Form values are POSTed to /controller/calculate.
  3. The Calculate action performs calculation based on input and instantiates a complex object containing the results of the operation. This object is stored in TempData and user is redirected to /controller/result.
  4. /controller/result retrieves the result from TempData and renders them to the user.

The problem with this approach is that if the user hits F5 while viewing the results in /controller/result the page can no longer be rendered as TempData has been expired and the result object is no longer available.

This behavior is not desired by the users. One possible solution would be instead of redirecting after the POST, just rendering the results view. Now if the user hits F5 he gets a browser dialog asking if he wants to repost the form. This also was not desired.

One possible solution I thought of was to serialize the result object and passing it in the URL before redirecting but AFAIK there are some limitations in the length of a GET request and if the object gets pretty big I might hit this limitation (especially if base64 encoded).

Another possibility would be to use the Session object instead of TempData to persist the results. But before implementing this solution I would like to know if there's a better way of doing it.


UPDATE:

Further investigating the issue I found out that if I re-put the result object in TempData inside the /controller/result action it actually works:

public ActionResult Result()
{
    var result = TempData["result"];
    TempData["result"] = result;
    return View(result);
}

But this feels kind of dirty. Could there be any side effects with this approach (such as switching to out-of-process session providers as currently I use InProc)?

like image 381
Darin Dimitrov Avatar asked Oct 14 '09 17:10

Darin Dimitrov


1 Answers

Store it in the Session with some unique key and pass the key as part of the url. Then as long as the session is alive they can use the back/forward button to their heart's content and still have the URL respond properly. Alternatively, you could use the ASP cache, but I'd normally reserve that for objects that are shared among users. Of course, if you used the parameters to the calculation as the key and you found the result in the cache, you could simply re-use it.

like image 77
tvanfosson Avatar answered Sep 23 '22 04:09

tvanfosson