10

我正在使用带有详细视图的 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))

有人可以请飞机为什么这不起作用?

4

3 回答 3

21

你不需要使用Html.DisplayFor,因为它会返回MvcHtmlString所以string.Format不适用。

只需string.Format在您的模型上使用:

@String.Format("{0:c}", Model.MonthlyMortgage)

请注意,您不再需要“$”符号,因为它{0:c}会处理它。

于 2012-06-24T08:10:57.700 回答
10

@nemesv 有一个直接的答案。另一种选择是 String.Format()从视图中删除并使用 DataAnnotations 将格式附加到 MonthlyMortgage。

来自 MSDN 的示例:

[DisplayFormat(DataFormatString = "{0:C}")]
public Decimal ListPrice { get; set; }

顺便说一句,#,###,###,##0.000可以缩短为#,##0.00

于 2012-06-24T08:13:23.060 回答
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; }
于 2021-03-15T17:10:14.593 回答