我有一个表单,允许用户输入数据并提交。如果在此操作结果上一切正常,我将把用户重定向回到感谢页面。我的问题是,当用户单击返回按钮时,他们仍然可以返回到表单页面,并且输入仍然存在。如果用户再次点击提交,可能会出现一些奇怪的错误。因此,在ASP.NET MVC方面,处理单击返回按钮的用户的最佳方法是什么?谢谢!
这个解决方案既适用于整个控制器,也适用于特定的操作,只需添加 [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();
}
}
而在你的代码中:
[NoCache]
[Authorize]
public class AccountController : Controller
{ ... }
此内容最初发布于: MVC 返回按钮问题
“潜在的奇怪错误”是什么意思?我怀疑用户会再次点击提交,除非他们想再次发布完全相同的内容。如果您不希望出现重复的帖子,请在发布之前检查内容是否与您的数据库中的内容相同。
如果您真的不希望人们两次发布相同的表单,请将一个随机生成的数字(只需确保它足够随机以避免冲突,或者使用用户ID和精确时间戳的组合)放入隐藏字段中,将其保存到数据中,并在保存任何内容之前检查它是否已经存在于您的数据库中。
@using (Html.BeginForm("FindResults", "COntrollerName", FormMethod.Get, new { id = "SearchForm" }))
{}
public ActionResult Index()
{
return view();
}
[HttpGet]
public ActionResult FindResults(FindIssueModel model)
{
}