私が含めたコードの量をお詫び申し上げます。最小限に抑えるように努めてきました。
モデルにカスタム バリデーター属性とカスタム モデル バインダーを設定しようとしています。Attribute と Binder は別々にうまく機能しますが、両方ある場合、Validation Attribute は機能しなくなります。
読みやすくするために切り取ったコードを次に示します。global.asax のコードを省略した場合、カスタム検証は起動しますが、カスタム バインダーを有効にしている場合は起動しません。
検証属性。
public class IsPhoneNumberAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//do some checking on 'value' here
return true;
}
}
私のモデルでの属性の使用;
[Required(ErrorMessage = "Please provide a contact number")]
[IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")]
public string Phone { get; set; }
カスタム モデル バインダー;
public class CustomContactUsBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ContactFormViewModel contactFormViewModel = bindingContext.Model as ContactFormViewModel;
if (!String.IsNullOrEmpty(contactFormViewModel.Phone))
if (contactFormViewModel.Phone.Length > 10)
bindingContext.ModelState.AddModelError("Phone", "Phone is too long.");
}
}
グローバル asax;
System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] =
new CustomContactUsBinder();