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 when I use @HTML.EditorFor(model => model.Double_attribute)
and test my application I can't type a double in that editor, I only can type integers. (I'm using Razor engine for views)How to solve this? Thanks.
Update : I discovered that I can type a double having this format #,### (3 numbers after the comma but I do not want to make user type a specific format, I want to accept all formats (1 or more numbers after the comma) Does anyone have an idea how to solve this? Regards
You could use add notations :
[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Double_attribute{ get; set; }
And now... voila : you can use the double in your view :
@Html.EditorFor(x => x.Double_attribute)
For other formats you could check this or just google "DataFormatString double" your desired option for this field.
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() );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.