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