MVC 3 doesn't bind nullable long

前端 未结 5 1529
执笔经年
执笔经年 2021-02-03 10:04

I made a test website to debug an issue I\'m having, and it appears that either I\'m passing in the JSON data wrong or MVC just can\'t bind nullable longs. I\'m using the latest

5条回答
  •  感动是毒
    2021-02-03 10:56

    If you don't want to go with Regex and you only care about fixing long?, the following will also fix the problem:

    public class JsonModelBinder : DefaultModelBinder {     
      public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)  
      {
            var propertyType = propertyDescriptor.PropertyType;
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                var provider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (provider != null 
                    && provider.RawValue != null 
                    && Type.GetTypeCode(provider.RawValue.GetType()) == TypeCode.Int32) 
                {
                    var value = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(provider.AttemptedValue, bindingContext.ModelMetadata.ModelType);
                    return value;
                }
            } 
    
            return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
      }
    }
    

提交回复
热议问题