DataType.Currency attribute does not work on $ sign

Working in ASP.NET MVC, I have a view model with a Sum field. The amount field is marked as a currency type using a data annotation similar to this ...

[DisplayName("My Amount")]
[DataType(DataType.Currency)]
public decimal? Amount { get; set; }

I also format the amount as the currency in the view using the format string ...

<%: Html.TextBox("Amount", string.Format("{0:c0}", Model.Amount)) %>

This causes the amount to be formatted as $ 100 when it is displayed in the view.

However, when the Amount is sent back to the server, the "$" inserted in the format string causes the verification of the amount to fail as a currency. Can someone tell me how to set this up so that I still have the amount formatted with "$", but it will also be checked as a currency?

+3
source share
1 answer

When you return the string "$ 100", run it Decimal.TryParse () , assigning the result to your Amountproperty (note that TryParse returns its decimal sum, if successful, in the parameter out, its return value is logical). You can specify NumberStyle(see Examples at this link) that will process the $ sign.

+2
source

Source: https://habr.com/ru/post/1781520/


All Articles