How do I format decimal as Percentage in EF Code First rendered in Razor TextBoxFor?
10,228
You could decorate your view model property with the [DisplayFormat]
attribute allowing you to specify a format:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:P2}")]
public decimal myProperty { get; set; }
and in your view:
@Html.EditorFor(x => x.myProperty)
But be careful because the DisplayFormat attribute (as it name suggests) is used only for displaying purposes. It is not used by the default model binder. So when the user submits this value by posting the form chances are you will get a validation error because for example 0.45%
is not a valid decimal value. I have illustrated in this post
how a custom model binder could be defined which will use the format defined by the DisplayFormat attribute when binding back the value.
Author by
Bill Software Engineer
I am a professional software developer working in San Francisco, USA.
Updated on June 04, 2022Comments
-
Bill Software Engineer almost 2 years
I have a property:
public decimal myProperty { get; set; }
And here is my render:
@Html.TextBoxFor(m => m.myProperty , new { @class = "percentage" })
How do I do the Percentage?
-
Darin Dimitrov about 11 yearsThis won't work. Only simple lambda expressions are supported by the strongly typed helpers.
-
Bill Software Engineer about 11 yearsSounds good, now is there anyway to apply a CSS class to EditorFor? I kind of need the css class.