Asp.net mvc 在表单字段未验证时单击“提交”按钮,从浏览器返回URL

Asp.net mvc 在表单字段未验证时单击“提交”按钮,从浏览器返回URL,asp.net-mvc,forms-authentication,Asp.net Mvc,Forms Authentication,当表单字段未验证时,单击“提交”按钮可从浏览器中返回URL 单击“提交”按钮之前,浏览器看起来像 单击“提交”按钮后(表单字段在之前不会被验证),浏览器看起来像这样 如何在点击提交按钮后保持与登录后相同的浏览地址,并将其重定向到该页面 这是行动代码 [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model, string returnUrl) {

当表单字段未验证时,单击“提交”按钮可从浏览器中返回URL

单击“提交”按钮之前,浏览器看起来像

单击“提交”按钮后(表单字段在之前不会被验证),浏览器看起来像这样

如何在点击提交按钮后保持与登录后相同的浏览地址,并将其重定向到该页面

这是行动代码

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
            model.UserName,
            DateTime.Now,
            DateTime.Now.AddMinutes(30), // value of time out property
            false, // Value of IsPersistent property
            String.Empty,
            FormsAuthentication.FormsCookiePath);
            string encTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            Response.Cookies.Add(faCookie);
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return RedirectToLocal(returnUrl ?? Url.Action("Index", "Home"));
        }
        else
        {
            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View();
        }
    }
    else
    {
        return View(model);
    }
}

提前感谢

我想看看
公共操作结果登录(LoginModel模型,string returnUrl)
方法中的
AccountController

您可以查看这篇SO文章:

假设您查看了

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) { ...
然后,当验证失败时,需要在操作方法中重新分配值

if (ModelState.IsValid)
{
  ....
}
else
{
  // If we got this far, something failed, redisplay form
  ModelState.AddModelError("", "The user name or password provided is incorrect.");
  ViewBag.ReturnUrl = returnUrl; // Add this line
  return View();
}

验证失败时,是否重新分配值?e、 g.
如果(!ModelState.IsValid){ViewBag.ReturnUrl=ReturnUrl;..
否@stephen。?但这是在采取行动之前发生的。我要更新我的问题,请现在检查一下,当你说“在采取行动之前…”时,你的意思是它根本没有击中方法吗是的,我想是这样的:(因为在我看来,这一切都是由jqueryval和jquery在验证之前完成的,可能我错了,请纠正我。如果(ModelState.IsValid)并检查,请在第一行上放置一个断点。谢谢你的回答,请检查我更新的问题。Stephen…我的观点有这一行。@using(Html.BeginForm)(“Login”,“Account”,FormMethod.Post,新的{id=“customForm”,ReturnUrl=ViewBag.ReturnUrl})没关系-我的答案仍然有效,关键问题是
。ReturnUrl=ViewBag.ReturnUrl..
当您重定向到此页面进行身份验证时,它的值是指定的,但是当您返回视图时,您需要重新指定它,因为验证失败。我会按照您的建议执行操作,但问题是。ReturnUrl将为空n这就是为什么它没有分配给Viewbag.ReturnUrl。不知道为什么…如果我写这行。@使用(Html.BeginForm(new{ReturnUrl=Viewbag.ReturnUrl}))它对我有效,但必须分配id给表单,我用该id管理css。抱歉,刚才注意到你使用了错误的重载。它应该是“@使用(Html.BeginForm)(“Login”,“Account”,新的{ReturnUrl=ViewBag.ReturnUrl},FormMethod.Post,新的{id=“customForm”})