DataAnnotations" NotRequired"属性 [英] DataAnnotations "NotRequired" attribute

查看:207
本文介绍了DataAnnotations" NotRequired"属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型一种复杂的。

我有我的 UserViewModel 其中有几个属性,其中两个是家庭电话办公电话。这两种类型的 PhoneViewModel 。在 PhoneViewModel 国家code 区域code 编号所有字符串。我想使国家code 可选的,但区域code 强制性的。

这个伟大的工程。我的问题是,在 UserViewModel 办公电话是强制性的,而家庭电话不是

反正我有可以dissable 设置任何属性要求在 PhoneViewModel attributs功课属性?

我试过这样:

  [ValidateInput(假)]

但它仅用于类和方法。

code:

 公共类UserViewModel
{
    [需要]
    公共字符串名称{;组; }    公共PhoneViewModel家庭电话{搞定;组; }    [需要]
    公共PhoneViewModel办公电话{搞定;组; }
}公共类PhoneViewModel
{
    公共字符串国家code {搞定;组; }    公共字符串区code {搞定;组; }    [需要]
    公共弦数{搞定;组; }
}


解决方案

[更新2012/5/24使思路更清晰]

我不知道这是正确的做法,但我认为你可以扩展这一概念,并能创造一个更通用的/可重复使用的方法。

在ASP.NET MVC验证发生在绑定阶段。当你张贴的形式向服务器 DefaultModelBinder 是从请求信息创建模型实例,并添加验证错误的 ModelStateDictionary <一/ code>。

在你的情况,只要绑定与家庭电话的验证情况会火起来的我觉得的,我们不能做太多这个创建的自定义验证属​​性或相似类型的。

所有我想是不是在所有创建模型实例家庭电话属性时存在的形式提供任何值(区code国,code和数字或空),当我们控制,我们控制了验证,该绑定,我们必须创建一个自定义模型粘合剂的。

自定义模型粘合剂的我们正在检查,如果该属性是家庭电话如果表单包含任何值的属性,如果没有我们不要在属性绑定和验证将不会发生家庭电话。简单地说,值家庭电话将是空的 UserViewModel

 公共类CustomModelBinder:DefaultModelBinder
  {
      保护覆盖无效BindProperty(ControllerContext controllerContext,ModelBindingContext的BindingContext,的PropertyDescriptor PropertyDescriptor的)
      {
        如果(propertyDescriptor.Name ==家庭电话)
        {
          VAR形式= controllerContext.HttpContext.Request.Form;          VAR国家code =形式[HomePhone.Country code];
          VAR区域code =形式[HomePhone.Area code];
          变种数=形式[HomePhone.Number];          如果(string.IsNullOrEmpty(国家$ C $三)及;&安培; string.IsNullOrEmpty(区$ C $三)及;&安培; string.IsNullOrEmpty(号))
            返回;
        }        base.BindProperty(controllerContext,BindingContext中,PropertyDescriptor的);
      }
  }

最后,你必须注册在的global.asax.cs自定义模型粘合剂。

  ModelBinders.Binders.Add(typeof运算(UserViewModel),新CustomModelBinder());

所以,现在的你有需要UserViewModel作为参数的一个动作,

  [HttpPost]
 公益行动后(UserViewModel userViewModel)
 { }

我们的自定义模型粘合剂发挥作用和形式不适合在区域code国,code和数量张贴任何值家庭电话,将不会有任何验证错误和 userViewModel.HomePhone 为空。如果表单发布ATLEAST这些属性值中的任何一个,那么验证将发生在家庭电话预期。

I've a model kind of complicated.

I have my UserViewModel which has several properties and two of them are HomePhone and WorkPhone. Both of type PhoneViewModel. In PhoneViewModel I have CountryCode, AreaCode and Number all strings. I want to make the CountryCode optional but AreaCode and Number mandatory.

This works great. My problem is that in the UserViewModel WorkPhone is mandatory, and HomePhone is not.

Is there anyway I can dissable Require attributs in PhoneViewModel by setting any attributes in HomeWork property?

I've tried this:

[ValidateInput(false)]

but it is only for classes and methods.

Code:

public class UserViewModel
{
    [Required]
    public string Name { get; set; }

    public PhoneViewModel HomePhone { get; set; }

    [Required]    
    public PhoneViewModel WorkPhone { get; set; }
}

public class PhoneViewModel
{
    public string CountryCode { get; set; }

    public string AreaCode { get; set; }

    [Required]
    public string Number { get; set; }
}

解决方案

[UPDATED on 5/24/2012 to make the idea more clear]

I'm not sure this is the right approach but I think you can extend the concept and can create a more generic / reusable approach.

In ASP.NET MVC the validation happens at the binding stage. When you are posting a form to the server the DefaultModelBinder is the one that creates model instances from the request information and add the validation errors to the ModelStateDictionary.

In your case, as long as the binding happens with the HomePhone the validations will fire up and I think we can't do much about this by creating custom validation attributes or similar kind.

All I'm thinking is not to create model instance at all for HomePhone property when there are no values available in the form (the areacode, countrycode and number or empty), when we control the binding we control the validation, for that, we have to create a custom model binder.

In the custom model binder we are checking if the property is HomePhone and if the form contains any values for it's properties and if not we don't bind the property and the validations won't happen for HomePhone. Simply, the value of HomePhone will be null in the UserViewModel.

  public class CustomModelBinder : DefaultModelBinder
  {
      protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
      {
        if (propertyDescriptor.Name == "HomePhone")
        {
          var form = controllerContext.HttpContext.Request.Form;

          var countryCode = form["HomePhone.CountryCode"];
          var areaCode = form["HomePhone.AreaCode"];
          var number = form["HomePhone.Number"];

          if (string.IsNullOrEmpty(countryCode) && string.IsNullOrEmpty(areaCode) && string.IsNullOrEmpty(number))
            return;
        }

        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
      }
  }

Finally you have to register the custom model binder in global.asax.cs.

  ModelBinders.Binders.Add(typeof(UserViewModel), new CustomModelBinder());

So now of you have an action that takes UserViewModel as parameter,

 [HttpPost]
 public Action Post(UserViewModel userViewModel)
 {

 }

Our custom model binder come into play and of form doesn't post any values for the areacode, countrycode and number for HomePhone, there won't be any validation errors and the userViewModel.HomePhone is null. If the form posts atleast any one of the value for those properties then the validation will happen for HomePhone as expected.

这篇关于DataAnnotations&QUOT; NotRequired&QUOT;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆