Reputation: 4662
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:
[Required]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
[Display(Name = "Payment Amount")]
public decimal Amount { get; set; }
The DataFormatString
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?
Upvotes: 0
Views: 733
Reputation:
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" })
Upvotes: 2