我正在使用MVC验证来检查是否在数据库中使用名称和密码退出。即使我没有找到任何匹配的用户,ModelState.IsValid
也是如此。
if (objModel != null)
{
if (ModelState.IsValid && Membership.ValidateUser(objUsersModel.UserName, objUsersModel.Password))
{
Profile.Initialize(objUsersModel.UserName.Trim(), true);
FormsAuthentication.SetAuthCookie(objUsersModel.UserName, false);
return RedirectToAction("Index", "Home");
}
}
如何将此设置为false并在mvc视图中设置错误消息的值。这是我的MVC视图。
<form role="form">
<div class="form-group">
<label for="exampleInputEmail1">User Name </label>
<i class="fa fa-user"></i>
@Html.TextBoxFor(m => m.UserName, new { maxlength = 50, @class = "form-control" })
@Html.ValidationMessageFor(u => u.UserName)
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<i class="fa fa-lock"></i>
@Html.PasswordFor(m => m.Password, new { maxlength = 50, @class = "form-control" })
@Html.ValidationMessageFor(u => u.Password)
</div>
<div class="form-actions">
<label class="checkbox"> <input type="checkbox" class="uniform" value=""> Remember me</label>
<button type="submit" class="btn btn-danger">Submit</button>
</div>
</form>
答案 0 :(得分:3)
如果用户名和密码无效,则需要添加ModelState
错误并返回视图
if (!ModelState.IsValid)
{
return View(yourModel);
}
if (!Membership.ValidateUser(objUsersModel.UserName, objUsersModel.Password)
{
ModelState.AddModelError(string.Empty, "The user name or password is incorrect");
return View(yourModel);
}
....
return RedirectToAction("Index", "Home");
在视图中,包括
@Html.ValidationSummary(true)
显示消息