Detect Browser Refresh vs. Form Submit in ASP.Net MVC 2

*爱你&永不变心* 提交于 2019-12-14 03:58:16

问题


I have an ASP.Net questionnaire application that resubmits data to the same page, showing a different question each time. There are BACK and NEXT buttons to navigate between questions.

I would like to detect when the form is submitted due to a browser refresh vs. one of the buttons being pressed. I came across a WebForms approach but don't know how to apply those principals in an MVC 2 application since page events aren't available (as far as I know... I'm pretty new to Microsoft's MVC model).

How would one apply that principle to MVC 2? Is there a better way to detect refresh?


回答1:


You could use the redirect-after-post pattern with TempData. Example:

  1. The Back and Next buttons POST a form to a controller action
  2. The controller action puts some state into the TempData and redirects to another controller action which will verify that the data is in TempData and return the view
  3. The user presses F5 on the browser, the previous action is called on GET and as the state is no longer into TempData you know the user pressed F5 and didn't pass through the form submission.

And to illustrate this:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var state = TempData["state"];
        if (state == null) 
        {
            // the user directly arrived on this action without passing 
            // through the form submission
        }
        return View();
    }

    [HttpPost]
    public ActionResult Index(string back)
    {
        TempData["state"] = new object();
        return RedirectToAction("Index");
    }
}


来源:https://stackoverflow.com/questions/2918651/detect-browser-refresh-vs-form-submit-in-asp-net-mvc-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!