How to handle form submission ASP.NET MVC Back button?

前端 未结 3 1277
梦如初夏
梦如初夏 2020-12-11 06:44

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 pag

相关标签:
3条回答
  • 2020-12-11 07:01

    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

    0 讨论(0)
  • 2020-12-11 07:14

    Use this code

    @using (Html.BeginForm("FindResults", "COntrollerName", FormMethod.Get, new { id = "SearchForm" }))
    {}
    public ActionResult Index()
        {
    return view();
    }
    [HttpGet]
        public ActionResult FindResults(FindIssueModel model)
        {
    }
    
    0 讨论(0)
  • 2020-12-11 07:15

    What do you mean by "potential weird bugs"? I doubt the user would click submit again unless they wanted to post exactly the same thing again. I you don't want duplicate posts, check the content against your DB before posting.

    If you really don't want people posting the same form twice, put a randomly generated number (just make sure it's random enough to avoid collisions, or use something like a combination of the user ID and a precise timestamp) into a hidden field, save that with your data and check that it doesn't already exist in your DB before saving anything.

    0 讨论(0)
提交回复
热议问题