Frage

Ich entschuldige mich für die Menge an Code, den ich aufgenommen haben. Ich habe versucht, es auf ein Minimum zu halten.

Ich versuche, eine benutzerdefinierte Validator Attribut auf meinem Modell zu haben, sowie ein Bindemittel Benutzerdefinierte Modell. Das Attribut und die Binder Arbeit große separat, aber wenn ich beide haben, dann ist die Validierung Attribut nicht mehr funktioniert.

Hier ist mein Code zur besseren Lesbarkeit snipped. Wenn ich den Code auslassen in die Feuer benutzerdefinierte Validierung Global.asax aber nicht, ob ich das benutzerdefinierte Binder aktiviert ist.

Validierung Attribut;

public class IsPhoneNumberAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //do some checking on 'value' here
        return true;
    }
}

Useage des Attributs in meinem Modell;

    [Required(ErrorMessage = "Please provide a contact number")]
    [IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")]
    public string Phone { get; set; }

Benutzerdefinierte Modell Binder;

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

Globale asax;

System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] = 
  new CustomContactUsBinder();
War es hilfreich?

Lösung

Stellen Sie sicher, dass Sie die base Methode aufrufen:

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);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top