2

我有一个带有数字的模型,当它显示在我的视图中时,我想以特定方式对其进行格式化。

[DisplayFormat(DataFormatString = "{### ##}")] 
 [Display(Name = "Postnr")] 
 public string CustomerZip;

在视图中:

@Html.DisplayFor(modelItem => item.CustomerZip) 

在数据库中,值存储为#####,因此在尝试这种方法时出现错误:“输入字符串的格式不正确”。我认为(或者更确切地说是希望)DataFormatString 会为我重新格式化字符串。

任何有关如何以最佳方式做到这一点的建议都值得赞赏。

4

3 回答 3

3

一些东西:

  1. 需要使用DataFormatString{0:...} 索引器样式格式字符串,就像您在string.Format. 所以你需要做类似的事情[DisplayFormat(DataFormatString="{0:### ##}"]。如果大括号应该是文字,那么你会使用[DisplayFormat(DataFormatString="{{{0:### ##}}}")]. 然而...
  2. 字符串没有这样的格式字符#。这就是您要用于数字类型的内容。如果您将值存储为整数,那么您很幸运;只需将类型更改CustomerZip为int。
  3. 如果您不是将值存储为整数,而是作为字符串存储(通常不会像使用邮政编码那样),那么您就会遇到更多问题。就像我说的,您没有任何带有字符串的自定义格式选项。您需要将 CustomerZip 表示为您将定义的一些自定义类型,即 IFormattable。
于 2012-05-01T08:24:55.397 回答
1

使用以下格式:

"{0:### ##}"

请参阅 MSDN 页面上的示例http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.dataformatstring.aspx

于 2012-05-01T08:21:13.120 回答
1

像这样使用 Raw 函数:

@Html.Raw(item.Valor.ToString("##,###"))

它适用于任何类型的数据。

于 2019-01-23T20:21:47.673 回答