加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在自定义模型绑定器中检查属性属性

发布时间:2020-12-15 18:09:07 所属栏目:百科 来源:网络整理
导读:我想强制我的系统中的所有日期都有效,而不是将来,所以我在自定义模型绑定器中强制执行它们: class DateTimeModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { var value =
我想强制我的系统中的所有日期都有效,而不是将来,所以我在自定义模型绑定器中强制执行它们:
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;
        }
    }

}

现在,除了少数例外,我想允许将来有些日期

[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方法中是否存在该属性?

解决方法

在绑定Model属性期间,我们可以通过以下方式访问属性所有者:

bindingContext.ModelMetadata.ContainerType.

因此,下面的代码段应该为FutureFecha属性提供变量hasAttribute设置为true

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读