我在此处关注此主题的不同帖子,但我真的无法弄清楚如何使用MVC
在Ajax
中显示验证错误。
我这样做(使用Ajax.BeginForm
):
@using (Ajax.BeginForm("Login", "Account",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "body",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "loadingOverlay",
OnComplete = "AjaxBeginFormOnComplete",
OnSuccess = "AjaxBeginFormOnSuccess",
OnFailure = "AjaxBeginFormOnFailure"
}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.ValidationMessageFor(m => m.ErrorNotLogged);
<div class="row">
<div class="col-5 mx-auto">
<div class="card">
// input data and such
</div>
</div>
</div>
}
在Controller上,我添加了ModelState.AddModelError
:
public ActionResult Login(LoginViewModel model)
{
ModelState.AddModelError("ErrorNotLogged", "Error Message");
return PartialView(model);
}
这是ViewMmodel:
public class LoginViewModel
{
[Display(Name = "Email", ResourceType = typeof(Resources.Customs))]
[Required(ErrorMessageResourceType = typeof(Resources.Customs), ErrorMessageResourceName = "RequiredEmail")]
[EmailAddress(ErrorMessageResourceType = typeof(Resources.Customs), ErrorMessageResourceName = "InvalidEmail")]
public string Email { get; set; }
[Display(Name = "Password", ResourceType = typeof(Resources.Customs))]
[DataType(DataType.Password)]
[Required(ErrorMessageResourceType = typeof(Resources.Customs), ErrorMessageResourceName = "RequiredPassword")]
public string Password { get; set; }
[Display(Name = "KeepMeLoggedIn", ResourceType = typeof(Resources.Customs))]
public bool KeepMeLoggedIn { get; set; }
public string ErrorNotLogged { get; set; }
}
因此,我需要显示(在AJAX请求之后)使用AddModelError生成的(错误列表)。
它执行正确的Ajax调用。但是当响应完成时,我看不到任何错误返回,任何HTML,没有!我哪里错了?
尝试了不同的方面,但没有任何作用:
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.ValidationSummary(false)
ModelState.AddModelError("", "Error Message");
return PartialView("Login", model);
[Required]
public string ErrorNotLogged { get; set; }
我应该调用一些JS函数客户端吗?无论如何......我仍然无法看到带有“错误”范围和消息的html返回...
答案 0 :(得分:-1)
你应该把你的财产放在剃须刀里。尝试使用 @ Html.EditorFor 或 @ Html.TextBoxFor ,例如:
@Html.ValidationSummary(true)
@Html.ValidationMessageFor(m => m.ErrorNotLogged);
<div class="row">
<div class="col-5 mx-auto">
<div class="card">
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
</div>
</div>
尝试哪一个:
..., new AjaxOptions { }, new { @id = "MyID"
)提供ID后:
$('#MyID').valid(); $('#MyID').validate().errorList
(将返回
错误 - 只是检查验证是否正常工作)。 或强> 有关详情,请查看@ https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/adding-validation