MVC3 editor for double displaying scientific notation

I have a property of my model that is of type double. One of my elements has a value of 0.000028, but when my editable view is displayed, the editor for this value is displayed as 2.8e-005.

Besides the fact that it confuses my users, it also does not allow me to check the correctness of the expression

[Display(Name = "Neck Dimension")] [RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "Neck Dimension must be a Number")] [Range(0, 9999.99, ErrorMessage = "Value must be between 0 - 9,999.99")] [Required(ErrorMessage = "The Neck Dimension is required.")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:F20}")] public double? NeckDimension { get; set; } 

How do I display this field? I have this bit of code (shown below) that will display the decimal number as I want, but I'm not sure where to implement it.

  var dbltest = 0.000028D; Console.WriteLine(String.Format("{0:F20}", dbltest).TrimEnd('0')); 

I use the NeckDimension property in two places and edit the view and the view. Here is how they are displayed.

 @Html.TextBoxFor(model => model.NeckDimension, new { style = "width:75px;" }) @Html.DisplayFor(model => model.NeckHDimension) 

UPDATE Apparently DisplayFormat will not work with TextBoxFor. I tried changing my @ Html.TextBoxFor to Html.EditorFor and giving it a class, but it failed with the following exception.

 The model item passed into the dictionary is of type 'System.Double', but this dictionary requires a model item of type 'System.String' 

This old code still works:

 @Html.TextBoxFor(model => model.NeckDimension, new { style = "width:75px;" }) 

This code gave an exception:

 @Html.EditorFor(model => model.NeckDimension, new {@class = "formatteddecimal"}) 

It looks like my options fix it with javascript or fix it with an editor template, but I don’t have time to research and study the second option at this stage.

DECISION:

I created an editor template for double? in the following way.

 @model double? @{ var ti = ViewData.TemplateInfo; var displayValue = string.Empty; if (Model.HasValue) { displayValue = String.Format("{0:F20}", @Model.Value).TrimEnd('0'); } <input id="@ti.GetFullHtmlFieldId(string.Empty)" name="@ti.GetFullHtmlFieldName(string.Empty)" type="text" value="@displayValue" /> } 
+7
source share
1 answer

You can decorate a property in your model using the [DisplayFormat] attribute:

 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:F20}")] public double Foo { get; set; } 

and now in your strongly typed views it’s simple:

 @Html.DisplayFor(x => x.Foo) 

or if it is intended for editing:

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

Another possibility, if you want to apply this format for all doubles in your application or on the controller, is to write a custom template / editor .

+7
source

All Articles