ErocM ErocM - 1 year ago 165
C# Question

Formatting a TextBoxFor from Decimal to Dollar Amount

I have an amount field that I am pre populating. When I run the web app, it comes out as 125.4500. I tried to format it but I've had no luck.

Here is my PaymentModel:

[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
[Display(Name = "Payment Amount")]
public decimal Amount { get; set; }

seems to have no affect.

And my code on the form:

@Html.TextBoxFor(m => m.Amount, new { @class = "makePaymentTextRight width90" })

I tried this:

@Html.TextBoxFor(m => string.Format("{0:F2}",m.Amount), new { @class = "makePaymentTextRight width90" })

But that gave me this error:

System.InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

How do I get this to format to 2 decimal places?

Answer Source

The DisplayFormatAttribute is only respected when using the EditorFor() and DisplayFor() methods (using the inbuilt templates)

To format a value, use this overload of TextBoxFor() where the 2nd parameter is the format string

@Html.TextBoxFor(m => m.Amount, "{0:F2}", new { @class = "makePaymentTextRight width90" })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download