加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC 2中自定义模型绑定器的自定义验证属性

发布时间:2020-12-16 06:43:21 所属栏目:asp.Net 来源:网络整理
导读:我为我所包含的代码量道歉.我试图将它保持在最低限度. 我正在尝试在我的模型上使用自定义验证器属性以及自定义模型绑定器.属性和Binder分开工作很好,但如果我同时使用,则验证属性不再有效. 这是我的代码剪切的可读性.如果我省略了global.asax中的代码,则会启
我为我所包含的代码量道歉.我试图将它保持在最低限度.

我正在尝试在我的模型上使用自定义验证器属性以及自定义模型绑定器.属性和Binder分开工作很好,但如果我同时使用,则验证属性不再有效.

这是我的代码剪切的可读性.如果我省略了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.");
    }
}

全球性的;

System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] = 
  new CustomContactUsBinder();

解决方法

确保您正在调用基本方法:

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读