سمة التحقق من الصحة المخصصة مع موثق النموذج المخصص في MVC 2

StackOverflow https://stackoverflow.com/questions/3067204

سؤال

أعتذر عن مقدار الرمز الذي أدرجته. لقد حاولت الاحتفاظ بها إلى الحد الأدنى.

أحاول الحصول على سمة مخصصة مخصصة على النموذج الخاص بي بالإضافة إلى موثق طراز مخصص. تعمل السمة والوثق بشكل رائع بشكل رائع ولكن إذا كان لدي كلاهما ، فإن سمة التحقق من الصحة لم تعد تعمل.

هنا رمز الخاص بي تم قصه لقدرة على القراءة. إذا تركت الرمز في Global.asax ، فإن حرائق التحقق المخصصة ولكن ليس إذا تم تمكين الموثق المخصص.

سمة التحقق من الصحة ؛

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

useage من السمة في النموذج الخاص بي ؛

    [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();
هل كانت مفيدة؟

المحلول

تأكد من الاتصال 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