我正在使用带有详细视图的MVC3,需要显示格式化的美元金额,如$ 1,200.00。在这种情况下,控制器将MonthlyMortgage传递给视图。但是,下面的代码行不会显示正确的字符串格式。显示的是$ 1200.00,我需要的是$ 1,200.00。
我试过了:
$@String.Format("{0:c}", Html.DisplayFor(model => model.MonthlyMortgage))
我试过这个:
$@String.Format("{0:#,###,###,##0.000}", Html.DisplayFor(model => model.MonthlyMortgage))
有人可以告诉我为什么这不起作用?
答案 0 :(得分:13)
您无需使用Html.DisplayFor
,因为它会返回MvcHtmlString
,因此string.Format
不适用。
只需使用模型上的string.Format
:
@String.Format("{0:c}", Model.MonthlyMortgage)
请注意,您不再需要“$”符号,因为{0:c}
会处理它。
答案 1 :(得分:6)
@nemesv有直接的答案。另一种选择是从视图中删除String.Format()
并使用DataAnnotations将格式附加到MonthlyMortgage。
来自MSDN的一个例子:
[DisplayFormat(DataFormatString = "{0:C}")]
public Decimal ListPrice { get; set; }
顺便说一下,#,###,###,##0.000
可以缩短为#,##0.00
答案 2 :(得分:0)
另一个选项是 [DataType]
属性。
添加 DataAnnotations using System.ComponentModel.DataAnnotations;
和 using System.ComponentModel.DataAnnotations.Schema
,然后您可以在模型中执行类似操作。
[DataType(DataType.Currency)]
[Column(TypeName = "decimal(18, 2)")]
public decimal MonthlyMortgage{ get; set; }