我有一个带有显示 Index.aspx View 的 Index 操作的 HomeController。它有一个用户名/密码登录部分。当用户单击提交按钮时,它会 POST 到 AccountController 中的登录操作。
<% Html.BeginForm("Login", "Account", FormMethod.Post); %>
在该操作中,它测试用户名/密码的有效性,如果无效,则将用户发送回登录页面,并显示凭据错误的消息。
[HttpPost]
public ActionResult Login(LoginViewModel Model, string ReturnUrl)
{
User user = MembershipService.ValidateUser(Model.UserName, Model.Password);
if (user != null)
{
//Detail removed here
FormsService.SignIn(user.ToString(), Model.RememberMe);
return Redirect(ReturnUrl);
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
// If we got this far, something failed, redisplay form
return RedirectToAction("Index", "Home"); // <-- Here is the problem. ModelState is lost.
}
但问题是:ValidationSummary 总是空白,因为当我们 RedirectToAction 时我们丢失了模型。
所以问题是:如何在没有重定向的情况下将用户发送到不同 Controller 上的操作?
最佳答案
正如其他人所说,如果验证失败,通常会返回 View ,但是当您从帐户 Controller 调用时,您将需要指定 View 的完整路径
return View("~/Views/Home/Index.aspx", model);
或者
如果登录失败,通常会有一个单独的登录页面并重定向到该页面。两个页面都将提交相同的登录操作。例如,Facebook 就是这样做的。
或者
因为您只想显示错误消息
return RedirectToAction("Index", "Home", new { LoginAttempts = 1 });
然后在您的索引操作中阅读
LoginAttempts
参数并选择相应地显示错误消息。
关于asp.net-mvc - ASP.NET MVC - 如何从不同的 Controller 维护 ModelState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4522316/