I want to enforce that all dates in my system are valid and not in the future, so I enforce them inside the custom model binder:
class DateTimeModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
try {
var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
// Here I want to ask first if the property has the FutureDateAttribute
if ((DateTime)date > DateTime.Today) {
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "No se puede indicar una fecha mayor a hoy");
}
return date;
}
catch (Exception) {
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "La fecha no es correcta");
return value.AttemptedValue;
}
}
}
Now, for a few exceptions I want to allow some dates to be in the future
[Required]
[Display(Name = "Future Date")]
[DataType(DataType.DateTime)]
[FutureDateTime] <-- this attribute should allow the exception
public DateTime FutureFecha { get; set; }
This is the Attribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class FutureDateTimeAttribute : Attribute {
}
Now, the question: How can I check that the attribute is present inside the BindModel
method?
Radim Köhler
During binding of the Model properties, we have access to property owner via:
bindingContext.ModelMetadata.ContainerType
.
So the below snippet should give you variable hasAttribute
set to true for FutureFecha property
var holderType = bindingContext.ModelMetadata.ContainerType;
if (holderType != null)
{
var propertyType = holderType.GetProperty(bindingContext.ModelMetadata.PropertyName);
var attributes = propertyType.GetCustomAttributes(true);
var hasAttribute = attributes
.Cast<Attribute>()
.Any(a => a.GetType().IsEquivalentTo(typeof (FutureDateTime)));
if(hasAttribute) ...
}
来源:https://stackoverflow.com/questions/13878967/how-to-check-for-a-property-attribute-inside-a-custom-model-binder