MVC 3 doesn't bind nullable long

前端 未结 5 1453
执笔经年
执笔经年 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:47

    You can use this model binder class

    public class LongModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (string.IsNullOrEmpty(valueResult.AttemptedValue))
            {
                return (long?)null;
            }
            var modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                actualValue = Convert.ToInt64(
                    valueResult.AttemptedValue,
                    CultureInfo.InvariantCulture
                );
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }
            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
    }
    

    In Global.asax Application_Start add these lines

    ModelBinders.Binders.Add(typeof(long), new LongModelBinder());
    ModelBinders.Binders.Add(typeof(long?), new LongModelBinder());
    

提交回复
热议问题