How to check a property attribute inside an embedded binder

I want all dates on my system to be valid, and not in the future, so I force them inside the binding to a custom model:

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, with a few exceptions, I want 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 attribute

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class FutureDateTimeAttribute : Attribute { } 

Now the question is: How to check if an attribute is present inside the BindModel method?

+4
c # asp.net-mvc model-binding
source share
1 answer

When binding model properties, we have access to the property owner through:

bindingContext.ModelMetadata.ContainerType .

So, the snippet below should give the hasAttribute variable true for the 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) ... } 
+11
source share

All Articles