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

自古美人都是妖i 提交于 2020-01-01 09:23:11

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!