
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) ...} 总结 以上是内存溢出为你收集整理的c# – 如何在自定义模型绑定器中检查属性属性全部内容,希望文章能够帮你解决c# – 如何在自定义模型绑定器中检查属性属性所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)