Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for a property attribute inside a custom model binder

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?

like image 496
Eduardo Molteni Avatar asked Dec 14 '12 12:12

Eduardo Molteni


1 Answers

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) ...
}
like image 56
Radim Köhler Avatar answered Nov 14 '22 15:11

Radim Köhler