7

システム内のすべての日付が有効であり、将来ではないことを強制したいので、カスタム モデル バインダー内でそれらを強制します。

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

4

1 に答える 1

17

モデルプロパティのバインド中に、次の方法でプロパティ所有者にアクセスできます。

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) ...
}
于 2012-12-14T13:21:17.283 に答える