gri*_*egs 4 asp.net-mvc custom-validators custom-model-binder
我为我所包含的代码量道歉.我试图将它保持在最低限度.
我正在尝试在我的模型上使用自定义验证器属性以及自定义模型绑定器.属性和Binder分开工作很好,但如果我同时使用,则验证属性不再有效.
这是我的代码剪切的可读性.如果我省略了global.asax中的代码,则会启动自定义验证,但如果我启用了自定义绑定,则不会触发.
验证属性;
public class IsPhoneNumberAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//do some checking on 'value' here
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的模型中使用属性;
[Required(ErrorMessage = "Please provide a contact number")]
[IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")]
public string Phone { get; set; }
Run Code Online (Sandbox Code Playgroud)
定制模型粘合剂;
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
全球性的;
System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] =
new CustomContactUsBinder();
Run Code Online (Sandbox Code Playgroud)
确保您正在调用该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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2317 次 |
| 最近记录: |