如何为MVC EditorFor设置货币格式?

我必须使用货币格式显示项目金额的页面。 第一个是输入货币的地方,第二个是货币显示的地方。

我希望EditorFor显示一个R表示Rands然后我希望该值为十进制。

这是我的EditorFor:

@Html.EditorFor(model => model.TransactionModel.Price)

我尝试了很多不同的方法,无法工作。

通过下面的这个例子,它不知道第二行中的’CurrencyPrice’是什么。

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

我也在我的transactionModel中尝试了这些:

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

有人可以告诉我,我怎么能做到这一点?

现在我将接受任何工作方法。

使用MVC 4,您可以使用包含格式字符串的TextBoxFor方法:

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

在MVC 3及以下版本中:

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

EditorFor可能会也可能不会工作。 就个人而言,我遇到了问题。 如需更多灵感,请参阅此答案 。

我无法让上述内容为我工作。 这是我提出的使用模型上的数据注释工作的解决方案。

 [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)] 

我在这里得到了JohnM的RegEx。

这绝对不是每个人都难过的! 我非常惊讶我不得不花费大量精力在ASP.NET应用程序中validation货币! 什么应该花30秒,花了几个小时的研究和测试。