用于电话号码或社会安全号码的DisplayFormat.DataFormatString

时间:2012-06-11 13:27:03

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

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

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

2 个答案:

答案 0 :(得分:12)

以下内容应该有效,但请注意Ssn属性的类型差异。

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

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

注意,为了应用格式化,您需要在视图中使用以下html助手:

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

答案 1 :(得分:1)

如果类型是整数,则接受的答案很好,但是很多id最终被输入为字符串以防止丢失前导零。您可以通过将字符串分解为Substring来格式化字符串,并通过将其粘贴到DisplayTemplate中使其可重复使用。

/Shared/DisplayTemplates/内,添加名为Phone.vbhtml的模板:

@ModelType String
@If Not IsNothing(Model) AndAlso Model.Length = 10 Then
    @<span>@String.Format("({0}) {1}-{2}",
              Model.Substring(0, 3),
              Model.Substring(3, 3),
              Model.Substring(6, 4))</span>
Else
    @Model
End If

您可以通过以下几种方式调用此方法:

  1. 只需使用相同名称的数据类型注释模型上的属性:

    <DataType("Phone")> _
    Public Property Phone As String
    

    然后使用简单的DisplayFor

    进行呼叫
     @Html.DisplayFor(Function(model) model.Phone)
    
  2. 或者,您可以按名称指定要使用的DisplayTemplate:

     @Html.DisplayFor(Function(model) model.VimsOrg.Phone, "Phone")