Unable to enter double in text box

I am working on the mvc.net web application and I am using the Entity Framework to create the model. I have classes that contain attributes that are doubles. My problem is that when I use @HTML.EditorFor(model => model.Double_attribute)and test my application, I cannot type double in this editor, I can type integers. (I use the Razor engine for views). How to solve this? Thank.

Update: I found that I can enter a double having this format #, ### (3 numbers after the decimal point, but I do not want the user to enter a specific format, I want to accept all formats (1 or more numbers after the decimal point) Anyone have an idea how to solve this?

+5
source share
2 answers

You can use additional notations:

[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Double_attribute{ get; set; }

And now ... voila: you can use double in your view:

@Html.EditorFor(x => x.Double_attribute)

For other formats, you can check this or just google "DataFormatString double", which you need for this field.

+2
source

try using a custom data block:

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 the binder in global.asax:

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

All Articles