这是与 Assign ValidationResult to specific field? 类似的问题
我的 View 模型如下所示:
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required")]
[StringLength(3, ErrorMessage = "Password length Should be less than 3")]
public string Password { get; set; }
[DisplayName("Confirm Password")]
[Required(ErrorMessage = "Confirm Password is required")]
[StringLength(3, ErrorMessage = "Confirm Password length should be less than 3")]
public string ConfirmPassword { get; set; }
public static ValidationResult ExtendedValidation(ManageUserViewModel t)
{
if (t.Password == t.ConfirmPassword)
return ValidationResult.Success;
else
return new ValidationResult("Your passwords must match", new[] { "ConfirmPassword" });
}
我的观点是这样的:
@Html.ValidationSummary(true, "The user details were not saved, please see the validation results below")
@using (Html.BeginForm("Save", "Users", FormMethod.Post))
{
<div class="formField">
@Html.LabelFor(model => model.Password)
@Html.TextBoxFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="formField">
@Html.LabelFor(model => model.ConfirmPassword)
@Html.TextBoxFor(model => model.ConfirmPassword)
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
但是我的自定义验证错误显示在页面顶部,当我希望它在线显示时。
EG,长度检查错误导致在线显示,我希望我的确认也这样做。
谢谢, 戴夫
最佳答案
有一个验证属性可以准确地完成您想要通过自定义验证实现的目标。尝试添加 Compare
属性:
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required")]
[StringLength(3, ErrorMessage = "Password length should be less than 3")]
public string Password { get; set; }
[DisplayName("Confirm Password")]
[Compare("Password", ErrorMessage = "Your passwords must match")]
[Required(ErrorMessage = "Confirm Password is required")]
[StringLength(3, ErrorMessage = "Confirm Password length should be less than 3")]
public string ConfirmPassword { get; set; }
另外...
有时我想添加其他我想使用 Html.ValidationMessage()
显示的错误。在服务器端验证期间将错误添加到 ModelState
。该 key 与正在验证的控件的 ID 相匹配,但您也可以添加自己的 key 。
你可以使用:
ModelState.AddModelError("ConfirmPassword", "You've done something wrong...");
向 ConfirmPassword
属性添加错误,然后将显示 ConfirmPassword
的验证错误。或者您可以使用不同的 key :
ModelState.AddModelError("MyError", "You've done something wrong...");
然后您可以使用以下方法在您的 View 中显示该错误:
@Html.ValidationMessage("MyError");
关于c# - 在线显示 ValidationResult 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259730/