String.Format for currency on a TextBoxFor
Asked Answered
R

3

21

I am trying to get @String.Format("{0:0.00}",Model.CurrentBalance) into this @Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance" })

I just want the currency to show up as .00 inside of my textbox but am having no luck. Any ideas on how I do this?

Reeve answered 5/8, 2011 at 23:4 Comment(0)
P
31

string.format("{0:c}", Model.CurrentBalance) should give you currency formatting.

OR

@Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance", Value=String.Format("{0:C}",Model.CurrentBalance) })

Polybasite answered 5/8, 2011 at 23:14 Comment(6)
@Html.TextBoxFor(String.Format("{0:C}",model => model.CurrentBalance), new { @class = "required numeric", id = "CurrentBalance" })....Is this the style I am looking for?Reeve
@Html.TextBoxFor(model => model.CurrentBalance, new { @class = "required numeric", id = "CurrentBalance", Value=String.Format("{0:C}",Model.CurrentBalance) })...This is what I was looking for. Thank you for the help:)Reeve
It is worthwhile to note the currency notation is dependent on your region settings. In parts of Europe you will get $1.000.000,00 for one million dollars, and depending on the settings you could get ($20.00) or -$20.00 for negatives.Tanka
Why the heck the 'v' in Value has to be capital?Lemniscate
This is a hack. It works only because "Value" takes precedence over "value". This shouldn't be the accepted answer.Ungrateful
Please use Gail Foad's answer instead. There is a parameter overload for TextBoxFor that accepts a string formatter, that is much better than calculating the format when setting it from the model.Theorem
V
22
@Html.TextBoxFor(model => model.CurrentBalance, "{0:c}", new { @class = "required numeric", id = "CurrentBalance" })

This lets you set the format and add any extra HTML attributes.

Vegetate answered 27/4, 2016 at 13:35 Comment(3)
Consider adding an explanation to your answer.Autohypnosis
This is the correct answer. The currently accepted answer is a hack. It results in the 2 value attributes, "Value" and "value".Ungrateful
format specification - learn.microsoft.com/en-us/dotnet/standard/base-types/…Turkic
P
2

While Dan-o's solution worked, I found an issue with it regarding the use of form-based TempData (see ImportModelStateFromTempData and ExportModelStateToTempData). The solution that worked for me was David Spence's on a related thread.

Specifically:

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

Now if you use EditorFor in your view the format specified in the annotation should be applied and your value should be comma separated:

<%= Html.EditorFor(model => model.Price) %>
Practitioner answered 12/2, 2015 at 20:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.