DataAnnotations “NotRequired” attribute

后端 未结 4 1322
天涯浪人
天涯浪人 2021-02-13 19:13

I\'ve a model kind of complicated.

I have my UserViewModel which has several properties and two of them are HomePhone and WorkPhone

4条回答
  •  醉梦人生
    2021-02-13 19:43

    Just some observation: the following code couse a problem if the binding is more than simple filed. I you have a case that in object have nested object it going to skip it and caouse that some filed not been binded in nested object.

    Possible solution is

    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
         {
             if (!propertyDescriptor.Attributes.OfType().Any())
             {
                 var form = controllerContext.HttpContext.Request.Form;
    
                 if (form.AllKeys.Where(k => k.StartsWith(string.Format(propertyDescriptor.Name, "."))).Count() > 0)
                 {
                     if (form.AllKeys.Where(k => k.StartsWith(string.Format(propertyDescriptor.Name, "."))).All(
                             k => string.IsNullOrWhiteSpace(form[k])))
                         return;
                 }
             }
    
             base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
         }
    

    much thanks to Altaf Khatri

提交回复
热议问题