Mvc3登录表单错误的用户名和密码消息
本文关键字:密码 消息 用户 登录 表单 错误 Mvc3 | 更新日期: 2023-09-27 18:16:05
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
Authenticate(model.Username, model.Password);
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
private void Authenticate(string userName, string password)
{
const string commaSeperatedRoles = "Administrator,Editor";
if (userName == "xx" && password == "xxx")
{
FormsAuthenticationUtil.RedirectFromLoginPage(userName, commaSeperatedRoles, false);
}
}
和LoginModel
public class LoginModel
{
[Required(ErrorMessage="*")]
[StringLength(10)]
public string Username { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(10)]
public string Password { get; set; }
}
和视图
@using (Html.BeginForm())
{
<table width="100%">
<tr>
<td>Username:</td>
<td>
@Html.TextBoxFor(m => m.Username, new { @style = "width: 140px;" })
</td>
</tr>
<tr>
<td>Passwd:</td>
<td>
@Html.PasswordFor(m => m.Password, new { @style = "width: 140px;" })
</td>
</tr>
</table>
<div class="napaka">Wrong username and password</div>
<br />
<input type="submit" class="button" value="Login" />
}
但是现在我总是得到这个错误的信息登录"错误的用户名和密码"。用户名和密码都错了,怎么才能写这条消息?我在c#中使用mvc3。我能以某种方式发送bool变量到视图或什么是sbet方式?
如果凭据错误,则向模型状态添加错误消息:
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
if (Authenticate(model.Username, model.Password))
{
// authentication was successful. The method created the cookie
// so we can safely redirect to an authenticated page here
return RedirectToAction("Index");
}
else
{
// authentication failed due to wrong username or password =>
// we add an error message to the ModelState here so that we
// can show it in the view
ModelState.AddModelError("", "Wrong username and password");
}
}
// At this stage we know that some error happened =>
// we redisplay the view so that the user can fix it
return View(model);
}
private bool Authenticate(string userName, string password)
{
const string commaSeperatedRoles = "Administrator,Editor";
if (userName == "xx" && password == "xxx")
{
// Warning: you should not be redirecting here. You should only
// create and set the authentication cookie. The redirect should be done
// in an MVCish way, i.e. by returning a RedirectToAction result if this
// method returns true
FormsAuthenticationUtil.SetAuthCookie(userName, commaSeperatedRoles, false);
return true;
}
// wrong username or password
return false;
}
,在视图中,不要在div中硬编码错误消息,而是使用ValidationSummary帮助器:
@using (Html.BeginForm())
{
<table width="100%">
<tr>
<td>Username:</td>
<td>
@Html.TextBoxFor(m => m.Username, new { @style = "width: 140px;" })
</td>
</tr>
<tr>
<td>Passwd:</td>
<td>
@Html.PasswordFor(m => m.Password, new { @style = "width: 140px;" })
</td>
</tr>
</table>
@Html.ValidationSummary(false)
<br />
<input type="submit" class="button" value="Login" />
}