Can not type a double in a textbox

前端 未结 2 1487
野趣味
野趣味 2021-01-18 23:49

I\'m working on an mvc .net web application and I\'m using Entity Framework for generating Model. I have classes that contain attributes that are doubles. My problem is that

2条回答
  •  [愿得一人]
    2021-01-19 00:26

    try to use custom databinder:

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

    and register binder in global.asax:

    protected void Application_Start ()
    {
        ...
        ModelBinders.Binders.Add( typeof( double ), new DoubleModelBinder() );
    }
    

提交回复
热议问题