Benutzerdefinierte Validierung Attribut mit benutzerdefinierten Modell Binder in MVC 2
-
28-09-2019 - |
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();
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);
}