モデルレベルの検証属性の作成サンプル モデルクラス [EndDateValidation] public class CustomDate { [DisplayFormat(DataFormatString = "0:dd-MM-yyyy}")] public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } [Required] public string Test { get; set; } } 検証属性クラス [AttributeUsage(AttributeTargets.Property|AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class EndDateValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { CustomDate date = value as CustomDate; return date.EndDate > date.StartDate ? true : false; } } Binderクラス public class CustomDateBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { //base.OnModelUpdated(controllerContext, bindingContext); IDataErrorInfo errorProvider = bindingContext.Model as IDataErrorInfo; if (errorProvider != null) { string errorText = errorProvider.Error; if (!String.IsNullOrEmpty(errorText)) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorText); } } foreach (ModelValidator validator in bindingContext.ModelMetadata.GetValidators(controllerContext)) { foreach (ModelValidationResult validationResult in validator.Validate(null)) { bindingContext.ModelState.AddModelError(CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName), validationResult.Message); } } } } コントローラ public ActionResult TestValidator() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult TestValidator([ModelBinder(typeof(CustomDateBinder))]CustomDate date) { return View(); } セシウム137を97.7%吸着 コメント: |