我有一个视图模型
[CustomValidation(typeof(MyValidation), "MyMethod")]
[Serializable()]
public class TransactionViewModel
{
public string InvoiceNumber;
}
public class MyValidation
{
public static ValidationResult validatelength(TransactionViewModel length)
{
bool isValid;
if (length.InvoiceNumber.Length >15)
isValid = false;
else
isValid = true;
if (isValid)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(
"The Field value is greater than 15");
}
}
}
现在我正在检查我的类对象的一些字段,如果验证失败我正在检查控制器中的模型状态并返回视图,添加了发票号的验证消息但仍然没有得到错误
我们可以将验证属性应用于模型视图,如果我做错了,PLS会提供解决方案
答案 0 :(得分:1)
使用
<%= this.Html.ValidationSummary() %>
或
@this.Html.ValidationSummary()
并且您将获得您正在寻找的内容。
如果您的模型状态无效,您将收到您正在寻找的错误。
您的问题是您的错误是您的错误未与班级的任何成员相关联。在模型状态中它有关键&#34;&#34;因为它与任何领域都没有联系。
答案 1 :(得分:0)
也许您忘记在您的视图上放置验证页?
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
请提交您的观点以供审核。同时在这里你是它工作的好例子: Validation with the Data Annotation Validators (C#)
Model validation from Scott's blog
在这里查看本教程handling model error,但使用空字符串作为密钥:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
错误消息将出现在&lt;%:Html.ValidationSummary()%&gt;正如你所料。