How to set up currency format for MVC EditorFor?

2019-08-02 20:58发布

I have to pages that need to show the item amount with currency format. The first one is where currency is entered and the second one where currency is displayed.

I would like the EditorFor to show an R indicated Rands and then i would like the value to be decimal.

Here is my EditorFor:

<div class="editor-field">
    @Html.EditorFor(model => model.TransactionModel.Price)
</div>

I have tried many different ways and can't get any to work.

With this example below it does not know what 'CurrencyPrice' is in the second line.

var CurrencyPrice = '@Model.TransactionModel.Price';
document.getElementById('TransactionModel.Price').value = '@string.Format("{0:C}", CurrencyPrice)'; 

I have also tried these in my transactionModel:

//[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
//[UIHint("Currency")]
//[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
//[DataType(DataType.Currency)]
public decimal Price { get; set; }

Could someone please tell me how i can get this right?

Right now i will accept any working method.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-02 21:13

With MVC 4, you can use the TextBoxFor method that includes a format string:

@Html.TextBoxFor(model => model.TransactionModel.Price, "{0:c}")

In MVC 3 and below:

@Html.TextBoxFor(model => model.TransactionModel.Price, 
    new { @Value = model.TransactionModel.Price.ToString("c") })

EditorFor might or might not work. Personally, I have had problems with it. For more inspiration, see this answer.

查看更多
狗以群分
3楼-- · 2019-08-02 21:21

I could not get the above to work for me. This is the solution I came up with that worked using Data Annotation on the Model.

[Required]
[DisplayName("Average Yearly Salary")]
[Numeric]
[RegularExpression(@"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$", ErrorMessage = "The value must be in currency format ")]
[StringLength(12)]

I got the RegEx from JohnM here.

This should REALLY not be this hard for everyone! I was very surprised I had to put forth so much effort on validating currency in an ASP.NET application!!! What should have taken 30 seconds, took hours of research and testing.

查看更多
登录 后发表回答