Reputation: 1194
This is the field I have in my View Model:
public decimal MyValue { get; set; }
Here is how I show the value in a View:
@Html.EditorFor(model => model.MyValue)
I debugged all the way from DB and turned off all JS. I still get that model in View has value 12.34345, but the final value that is presented to a user is 12.34.
This question is asking HOW to tackle this but WHY is left unclear.
Interestingly, when I use:
@Html.HiddenFor(model => model.MyValue)
rounding is not happening.
Upvotes: 9
Views: 5712
Reputation: 391
Please take a look at below source code https://github.com/aspnet/Mvc/blob/6436538068d19c475d5f7c9ce3d0080d2314f69d/src/Microsoft.AspNetCore.Mvc.ViewFeatures/Internal/DefaultEditorTemplates.cs
see below method
public static IHtmlContent DecimalTemplate(IHtmlHelper htmlHelper)
{
if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue == htmlHelper.ViewData.Model)
{
htmlHelper.ViewData.TemplateInfo.FormattedModelValue =
string.Format(CultureInfo.CurrentCulture, "{0:0.00}", htmlHelper.ViewData.Model);
}
return StringTemplate(htmlHelper);
}
Upvotes: 1
Reputation:
It is a function of the default EditorTemplate
for decimal
. Form the source code (note the format is "{0:0.00}"
)
internal static string DecimalTemplate(HtmlHelper html)
{
if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model)
{
html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, "{0:0.00}", html.ViewContext.ViewData.ModelMetadata.Model);
}
return StringTemplate(html);
}
If you want to display the decimal places as saved, use @Html.TextBoxFor(m => m.MyValue)
, or you can apply your own format using the DisplayFormatAttribute
, which will be respected by the EditorFor()
method, for example
[DisplayFormat(DataFormatString = "{0:0.00000}", ApplyFormatInEditMode = true)]`
public decimal MyValue { get; set; }
Upvotes: 11