Using MVC5 and .NET 4.5
I want to make a DataTypeAttribute that will both use a Editor Template and work as a ValidationAttribute.
As I understand it, DataTypeAttribute inherits from ValidationAttribute so I didn't think this would be difficult.
However, I can't get it to validate.
Here is my attribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class XXXAttribute : DataTypeAttribute
{
public XXXAttribute() : base("XXX") { }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// validation code
}
}
Here is the property in my ViewModel:
[XXX]
[Display(Name = "XXX")]
public string XXX { get; set; }
A debugger in the IsValid method of my XXXAttribute shows that it is never being checked on submit.
Can someone point out to me what I've done wrong? Thank you.
The editor templates work on DataTypes naming convention. So you will need a string.cshtml (not recommended) or you can use the EditorFor override that explicitly tells it what template to use.
See documentation http://msdn.microsoft.com/en-us/library/ee407414(v=vs.118).aspx