MVC 2中使用自定义模型活页夹的自定义验证属性
-
28-09-2019 - |
题
对于我包含的代码量,我深表歉意。我试图将其保持在最低限度。
我正在尝试在我的模型和自定义模型活页夹上具有自定义验证器属性。属性和粘合剂可分开工作,但是如果我两者都有,那么验证属性将不再起作用。
这是我的代码可读性。如果我在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();
解决方案
确保您打电话给 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);
}
不隶属于 StackOverflow