问题
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:
- The Back and Next buttons POST a form to a controller action
- The controller action puts some state into the
TempData
and redirects to another controller action which will verify that the data is inTempData
and return the view - 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