Working in ASP.NET MVC, I have a view model with an Amount field. The amount field is tagged as a Currency type using a data annotation like so…
[DisplayName("My Amount")]
[DataType(DataType.Currency)]
public decimal? Amount { get; set; }
I am also formatting the Amount as currency in the view using a format string…
<%: Html.TextBox("Amount", string.Format("{0:c0}", Model.Amount)) %>
This results in the Amount being formatted as $100 when it is displayed in the view.
However, when the Amount is submitted back to the server the “$” inserted by the format string causes the Amount to fail validation as currency. Can anyone tell me how to set this up so that I may still have the Amount formatted with a “$” but it will also validate as a currency?
When you pull that “$100” string back in, run it through Decimal.TryParse(), assigning the result to your
Amountproperty (note that TryParse returns its decimal amount, if successful, in anoutparameter; its return value is boolean). You can specify aNumberStyle(see the examples at that link) which will deal with the $ sign.