String.Format for currency on a TextBoxFor

2019-04-18 05:38发布

问题:

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?

回答1:

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



回答2:

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



回答3:

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