Asp.net-mvc – How to handle form submission ASP.NET MVC Back button

asp.netasp.net-mvcback-button

i have a form which allows the user to key in the data and then submit.
if everything works well on this action result, then i will redirect the user back to a thank you page.

my problem right now is that when the user click on the back button, they will be able to go back to the form page and the inputs will still be there.

and if the user just click on submit again, i will be getting some potential weird bugs.

so in terms of asp.net mvc, what's the best way to handle users who click on the back button?

thanks!

Best Answer

This solution works perfectly for both the whole controller or a specific action, simply add [NoCache]

 /// <summary>
 /// Prevent a controller or specific action from being cached in the web browser.
 /// For example - sign in, go to a secure page, sign out, click the back button.
 /// <seealso cref="https://stackoverflow.com/questions/6656476/mvc-back-button-issue/6656539#6656539"/>
 /// </summary>
public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var response = filterContext.HttpContext.Response;
        response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        response.Cache.SetValidUntilExpires(false);
        response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.SetNoStore();
    }
}

And in your code:

[NoCache]
[Authorize]
public class AccountController : Controller
{ ... }

Originally posted here: MVC Back button issue