DisplayFormat not getting applied on decimal value
Asked Answered
H

3

11

I have a model property I'm trying to render using an EditorFor template, and I'm trying to apply formatting using the DisplayFormat attribute. However, it's not working at all -- it's totally being ignored.

Here is my template:

@model System.Decimal?
@Html.TextBoxFor(m => m)

Here is my model:

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

Here is my view:

@Html.EditorFor(m => m.Retail)

But it's rendering a textbox with the following value:

189.9900

It seems pretty straight forward, but it's not working, and I have no idea why.

UPDATE: Just for kicks, I tried it with a DisplayFor template, and it worked:

@Html.DisplayFor(m => m.Retail)

So why would the DisplayFor template work, but not the EditorFor template, when I've set ApplyFormatInEditMode to true?

UPDATE 2: Never mind, the reason that worked is because my Decimal display template was hard-coded to format that way. So my display template also does not work.

Homoio answered 20/10, 2011 at 22:39 Comment(2)
Did you try @Html.EditorForModel() in your template?Timeserver
Yeah, that only removed the textbox altogether.Homoio
H
4

Darin Dimitrov posted this answer, and I was able to get it working using his solution:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue)

A bit crude, IMO, that this doesn't work w/ TextBoxFor, but at least it works.

Homoio answered 20/10, 2011 at 23:25 Comment(0)
E
4

Try with this format, it outputs 18.999,00

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N}")]
Eponym answered 20/10, 2011 at 22:54 Comment(3)
No, that still doesn't work for me. It still renders 1899.9900.Homoio
You must be using the default EditorFor template, whereas I'm using a custom template. Default templates work fine for me, it's the custom templates that don't work, as they have to ultimately use TextBoxFor. So my answer above, and the question I linked to.Homoio
as @jer says it works in EditorFor but not TextBoxForClod
H
4

Darin Dimitrov posted this answer, and I was able to get it working using his solution:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue)

A bit crude, IMO, that this doesn't work w/ TextBoxFor, but at least it works.

Homoio answered 20/10, 2011 at 23:25 Comment(0)
T
2

DisplayFormat won't work like that; if you manually create a text box for the property it doesn't come into play. It would only work if you did

@model System.Decimal?
@Html.DisplayFor(m => m)
Timeserver answered 20/10, 2011 at 22:41 Comment(1)
So does it not work with EditorFor? I thought that was the point of ApplyFormatInEditMode?Homoio

© 2022 - 2024 — McMap. All rights reserved.