我有一个带有数字I的模型,当我在视图中显示时,我希望以特定的方式进行格式化。
[DisplayFormat(DataFormatString = "{### ##}")]
[Display(Name = "Postnr")]
public string CustomerZip;
在视图中:
@Html.DisplayFor(modelItem => item.CustomerZip)
在DB中,值存储为#####,因此在尝试此方法时出现错误:"输入字符串格式不正确"。我想(或者更确切地说)DataFormatString会为我重新格式化字符串。
对于如何以最佳方式执行此操作的任何建议表示赞赏。
答案 0 :(得分:3)
一些事情:
DataFormatString
需要使用{0:...}索引器样式格式字符串,就像您在string.Format
中使用的那样。所以你需要做[DisplayFormat(DataFormatString="{0:### ##}"]
之类的事情。如果大括号应该是文字的,那么你可以使用[DisplayFormat(DataFormatString="{{{0:### ##}}}")]
。然而... #
。这就是你用于数字类型的东西。如果您将值存储为整数,那么您很幸运;只需将CustomerZip
的类型更改为int。答案 1 :(得分:1)
使用以下格式:
"{0:### ##}"
答案 2 :(得分:1)
像这样使用Raw函数:
@ Html.Raw(item.Valor.ToString(“ ##,###”))
它适用于任何类型的数据。