MVC 2 中使用自定义模型绑定器的自定义验证属性
对于我所包含的代码量,我深表歉意。我已经尽力将其保持在最低限度。
我试图在我的模型上有一个自定义验证器属性以及一个自定义模型绑定器。属性和活页夹单独工作效果很好,但如果我同时拥有两者,那么验证属性就不再起作用。
这是我为了可读性而剪掉的代码。如果我遗漏了 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();
I apologise for the amount of code I have included. I've tried to keep it to a minimum.
I'm trying to have a Custom Validator Attribute on my model as well as a Custom Model binder. The Attribute and the Binder work great seperately but if I have both, then the Validation Attribute no longer works.
Here is my code snipped for readability. If I leave out the code in global.asax the custom validation fires but not if I have the custom binder enabled.
Validation Attribute;
public class IsPhoneNumberAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//do some checking on 'value' here
return true;
}
}
Useage of the attribute in my model;
[Required(ErrorMessage = "Please provide a contact number")]
[IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")]
public string Phone { get; set; }
Custom Model 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.");
}
}
Global asax;
System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] =
new CustomContactUsBinder();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您正在调用
base
方法:Make sure you are calling the
base
method: