EditorFor and ApplyFormatInEditMode

459 views Asked by At

I'm working with MVC 5, and I'm having an issue formating decimal numbers

I have a decimal with 18,5 precision in my model and I want to show it for editing with EditorFor but it is ignoring the DataFormatString even though ApplyFormatInEditMode is true

[DisplayFormat(DataFormatString = "{0:#.#####}", ApplyFormatInEditMode = true)]
public decimal? Example{ get; set; }

Using the number 4 as example

if I render it as:

@Html.DisplayFor(x => x.Example) //result: 4 (this is what i want!)
@Html.TextBoxFor(x => x.Example) //result: 4.00000
@Html.EditorFor(x => x.Example) //result: 4.00000

how can I work with it?

Thanks!

1

There are 1 answers

1
AudioBubble On BEST ANSWER

The result of @Html.EditorFor(x => x.Example) will be 4, not 4.00000 when using the in-built default templates, therefore I can only assume that you must have a custom EditorTemplate defined for typeof decimal? (check the EditorTemplates folder in /Views/Shared and Views/YourControllerName folder for a file named Decimal.cshtml).

The result you see when using TextBoxFor() is correct. The [DisplatFormat] attribute is only respected when using DisplayFor() or EditorFor(). To format a value using TextBoxFor(), you need to use an overload that accepts a format string

@Html.TextBoxFor(m => m.Example, "{0:#.#####}") // result: 4