如何在引导模式对话框中使用MVC ValidationMessageFor



大家好,我有点麻烦问。。。我正试图使用ValidationMessageFor将错误消息输入登录引导模式dilog,但实际上不起作用,我不知道为什么。

这是我使用Html.BeginForm登录的dilog

<div class="col-xs-2 login-btn">
<a class="btn pfologin" data-toggle="modal" data-target=".bootstrapmodal">
<span> LOGIN</span>
</a>
<!-- Modal dialog -->
<div class="modal fade bootstrapmodal">
<div class="modal-dialog">
@using (Html.BeginForm("Login", "Account"))
{
<div class="modal-content modal-pfo">
<div class="modal-body">
<p>
User:<br />
@Html.TextBoxFor(s => s.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(s => s.Password, "", new { @class = "text-danger" })
</p>
<p>
Password:<br />
@Html.TextBoxFor(s => s.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(s => s.Password, "", new { @class = "text-danger" })
</p>
<p style="display: flex;">
@Html.CheckBoxFor(s => s.Privacy, new { @class = "checkbox" }) &nbsp;&nbsp;&nbsp;Remember me
</p>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-pfo">Cancel</button>
<input type="submit" value="Login" class="btn btn-pfo" />
</div>
</div>
}
</div>
</div>...

这是型号

public class LoginModel
{
[Required(ErrorMessage = "Username requested")]
public string Name { get; set; }
[Required(ErrorMessage = "Password requested")]
[DataType(DataType.Password)]
public string Password { get; set; }
public bool Privacy { get; set; }
}

这是控制器

[HttpPost]
public async Task<ActionResult> Login(LoginModel loginModel)
{
if (String.IsNullOrEmpty(loginModel.Name))
{
return ModelState.AddModelError("Name", loginModel.Name);
}
if (String.IsNullOrEmpty(loginModel.Password))
{
ModelState.AddModelError("Password", loginModel.Password);
}
if (ModelState.IsValid)
{
}
return RedirectToAction("Index", "Home");
}

是的,我从登录/发布重定向到索引,但我不认为这是问题所在。。。非常感谢。

当您返回RedirectToAction时,您将丢失所有表单数据(因此也会丢失所有验证信息(。返回带有传入模型的视图,而不是重定向到索引。

其次,因为这两个属性都标记为Required,所以不需要显式检查它们是null还是空的。根据您在模型上设置的属性,在到达[HttpPost]方法之前,模型已经过验证。如果返回带有此模型的视图,则会显示验证消息。这是最基本的实现,但您可能可以逃脱:

[HttpPost]
public async Task<ActionResult> Login(LoginModel loginModel)
{
if (ModelState.IsValid)
{
// Do work
return RedirectToAction("Index", "Home");
}
// Else, if not valid, re-render the view with the updated information and display it to the user
return View(loginModel);
}

有关验证的更多信息,请点击此处

最新更新