如何检查自定义模型粘合剂内属性特性 [英] How to check for a property attribute inside a custom model binder

查看:83
本文介绍了如何检查自定义模型粘合剂内属性特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要强制在我的系统的所有日期是有效的,而不是在未来,因此我执行这些自定义模型绑定内:

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; }

这是属性

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

}

现在,问题:?如何检查属性是 BindModel 方法内present

Now, the question: How can I check that the attribute is present inside the BindModel method?

推荐答案

在的结合的模型的性质,我们必须通过访问业主:

During binding of the Model properties, we have access to property owner via:

bindingContext.ModelMetadata.ContainerType

所以,下面的代码片段应该给你的变量 hasAttribute 设置为true的 FutureFecha 的属性

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) ...
}

这篇关于如何检查自定义模型粘合剂内属性特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆