Samjus
Samjus

Reputation: 675

String.Format for currency on a TextBoxFor

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?

Upvotes: 21

Views: 61743

Answers (3)

Gail Foad
Gail Foad

Reputation: 710

@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.

Upvotes: 23

cat5dev
cat5dev

Reputation: 1335

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) %>

Upvotes: 1

Sam Axe
Sam Axe

Reputation: 33738

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) })

Upvotes: 31

Related Questions