c# - 如何检查自定义模型 Binder 中的属性属性

标签 c# asp.net-mvc model-binding

我想强制我系统中的所有日期都是有效的而不是 future 的日期,所以我在自定义模型 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;
        }
    }

}

现在,对于一些异常(exception),我想允许一些日期在未来

    [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 属性绑定(bind)期间,我们可以通过以下方式访问属性所有者:

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# - 如何检查自定义模型 Binder 中的属性属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13878967/

相关文章:

C#- ASP.net MVC 3- 向表中插入多行

c# - 使用 C# 对 Excel 工作表运行 VBA 宏

c# - 从单独的线程访问表单的控件

javascript - 不破坏 JavaScript IntelliSense 的 ASP.NET MVC 相对路径?

c# - 回发后的模型绑定(bind)将 DateTime 属性设置为 NULL

c# - 如何在通用 Windows 平台中检查互联网连接类型

asp.net - 如何调试 ASP.NET 编译错误?

asp.net-mvc - 授权失败时将用户重定向到特定 View ?

razor - 如果嵌套在 View 模型中,则 IFormFile 未绑定(bind)

c# - Web Api 参数绑定(bind) : snake_case to camelCase