ASP.NET MVC - 如何从一个不同的控制器保持的ModelState? [英] ASP.NET MVC - How to maintain ModelState from a different controller?
问题描述
我用索引操作,显示的Index.aspx视图HomeController的。它有一个用户名/密码登录部分。当用户点击提交按钮,它POST到在一的AccountController登录操作。
I have a HomeController with an Index action that shows the Index.aspx view. It has a username/password login section. When the user clicks the submit button, it POSTs to a Login action in the AccountController.
<% Html.BeginForm("Login", "Account", FormMethod.Post); %>
在采取行动,它会检测用户名/密码的有效性和若无效,将用户返回到登录页面与消息的凭据是坏的。
In that action, it tests for Username/Password validity and if invalid, sends the user back to the Login page with a message that the credentials were bad.
[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
But here's the problem: the ValidationSummary is always blank because we're losing the Model when we RedirectToAction.
所以,问题是:如何向用户发送到不同的控制器上的动作没有重定向
推荐答案
正如其他人说,这是常见的,如果验证失败,返回的看法,但因为你是从您的账户控制器喊你会想指定视图的完整路径
As others have said it's common to return the view if validation fails but as you are calling from your account controller you will want to specify the full path of your view
return View("~/Views/Home/Index.aspx", model);
或者
它也是常见的有一个单独的登录页面,如果登录失败重定向到该网页。这两个页面将提交相同的登录操作。 Facebook的做这行的例子。
It is also common to have a seperate login page and redirect to that page if the login fails. Both pages will submit to the same login action. Facebook does this for example.
或者
当你只想显示一条错误消息
As you only want to display an error message
return RedirectToAction("Index", "Home", new { LoginAttempts = 1 });
然后在Index操作阅读 LoginAttempts
参数,并选择相应显示错误消息。
then in your Index action read the LoginAttempts
parameter and choose to display the error message accordingly.
这篇关于ASP.NET MVC - 如何从一个不同的控制器保持的ModelState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!