asp.net-mvc - 电话号码或社会保险号的 DisplayFormat.DataFormatString

标签 asp.net-mvc formatting data-annotations asp.net-mvc-4

有没有一种方法可以使用 View 模型属性上的 DisplayFormat 属性来为社会安全号码或电话号码应用 DataFormatString 格式?我知道我可以使用 javascript 来做到这一点,但如果可能的话,我更愿意让模型来处理它。

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "???????")]
public string Ssn { get; set; }

最佳答案

以下应该可以工作,但请注意 Ssn 属性的类型差异。

[DisplayFormat(DataFormatString = "{0:###-###-####}")]
public long Phone { get; set; }

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:###-##-####}")]
public long Ssn { get; set; }

请注意,为了应用格式,您需要在 View 中使用以下 html 帮助器:

@Html.DisplayFor(m => m.Property)

关于asp.net-mvc - 电话号码或社会保险号的 DisplayFormat.DataFormatString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10981049/

相关文章:

c# - ModelMetadata TemplateHint 始终为空

asp.net-mvc - 路由约束重定向

c# - 如何在 c# 中将 Decimal 格式化为程序控制的小数位数?

asp.net-mvc - Html.TextBoxFor 仅接受大于零的数字

html - 如何防止 HTML 删除空格?

perl - 如何在 Perl 中输出文本表?

c# - 将 Azure 网站本地化为特定文化

c# - MVC Controller 的 HttpContext 为空

c# - Entity Framework 查询一个逗号分隔的字段

c# - 在基本 Controller MVC 中实现逻辑