質問

含めたコードの量についてお詫び申し上げます。私はそれを最小限に抑えようとしました。

モデルにカスタムバリーター属性とカスタムモデルバインダーを用意しようとしています。属性とバインダーは別々に機能しますが、両方がある場合、検証属性は機能しなくなります。

これが私のコードを読みやすくするために切り分けました。 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.");
    }
}

グローバルアサックス;

System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] = 
  new CustomContactUsBinder();
役に立ちましたか?

解決

あなたが電話していることを確認してください base 方法:

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.");

    base.OnModelUpdated(controllerContext, bindingContext);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top