Search code examples
javascriptasp.netpost-redirect-get

Post/Redirect/Get with alert to user?


I have an ASP.NET WebForms application that process a post request and displays a message to the user via JavaScript alert (via ClientScript.RegisterStartupScript...). At some point after that client-side code executes that refreshes the page and of course I am getting "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier" or similar ones in other browsers.

Now, I know about Post/Redirect/Get pattern, but if I do redirect right after the post - I cannot display the JS alert. Is there a way to display alert and execute server-side redirect? I know I can add a specific querystring to redirect URL, check it on page load and display the alert if it's present, but that means if redirected page is refreshed - I will get that alert again, which is undesirable. Is there a way to do that that wouldn't involve complicated messy flags?


Solution

  • TempData in ASP.NET MVC is intended for redirects. If you store a message there you will be able to check for it and display it following a redirect. If the page is refreshed the value will not be persisted though, so won't be visible a second time, complementing the PRG pattern.

    I've seen it implemented as an extension for ActionResults, like in the FunnelWeb weblog source:

    https://github.com/funnelweblog/FunnelWeb/blob/f28d1b1cb9c86e492f120948309de68c12141222/src/FunnelWeb.Web/Application/Mvc/MvcExtensions.cs

    For WebForms, I believe the only option is to use Session and clear it after access, although you should be able to create a wrapper around it, like in the link above, which functions in the same way:

    equivalent of ASP.NET MVC TempData in ASP.NET