goe*_*ing 24 c# asp.net-mvc data-annotations
我有这样的事情:
[DisplayName("First Name")]
[Required(ErrorMessage="{0} is required.")]
[StringLength(50, MinimumLength = 10, ErrorMessage="{0}'s length should be between {2} and {1}.")]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想要以下输出:
它在使用ASP.NET MVC2错误摘要时有效,但当我尝试手动验证它时,如下所示:
ValidationContext context = new ValidationContext(myModel, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(myModel, context, results, true);
Run Code Online (Sandbox Code Playgroud)
结果是:
怎么了?谢谢.
Sor*_*sen 36
而不是(或可能与)一起使用[DisplayName]
属性,使用[Display]
in中的属性System.ComponentModel.DataAnnotations
.填充其Name
财产.
就这样,你可以使用内置的验证属性或自定义属性ValidationContext
的DisplayName
.
例如,
[Display(Name="First Name")] // <-- Here
[Required(ErrorMessage="{0} is required.")]
[StringLength(50, MinimumLength = 10, ErrorMessage="{0}'s length should be between {2} and {1}.")]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
goe*_*ing 11
好吧,我想我做到了.
我必须创建另一个属性,如下所示:
public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
private String displayName;
public RequiredAttribute()
{
this.ErrorMessage = "{0} is required";
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var attributes = validationContext.ObjectType.GetProperty(validationContext.MemberName).GetCustomAttributes(typeof(DisplayNameAttribute), true);
if (attributes != null)
this.displayName = (attributes[0] as DisplayNameAttribute).DisplayName;
else
this.displayName = validationContext.DisplayName;
return base.IsValid(value, validationContext);
}
public override string FormatErrorMessage(string name)
{
return string.Format(this.ErrorMessageString, displayName);
}
}
Run Code Online (Sandbox Code Playgroud)
我的模型是:
[DisplayName("Full name")]
[Required]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
值得庆幸的是,这个DataAnnotation是可扩展的.
归档时间: |
|
查看次数: |
19939 次 |
最近记录: |