DisplayFormat.DataFormatString for a phone number or social security number

折月煮酒 提交于 2019-11-30 12:45:25

The following should work, however notice the type difference for the Ssn property.

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

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

Note, that in order for the formatting to be applied you would need to use the following html helper in your view:

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

The accepted answer is great if the type is an integer, but a lot of ids wind up being typed as a string to prevent losing leading zeros. You can format a string by breaking it up into pieces with Substring and make it reusable by sticking it in a DisplayTemplate.

Inside /Shared/DisplayTemplates/, add a template named 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

You can invoke this in a couple ways:

  1. Just annotate the property on your model with a data type of the same name:

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

    And then call using a simple DisplayFor:

     @Html.DisplayFor(Function(model) model.Phone)
    
  2. Alternatively, you can specify the DisplayTemplate you'd like to use by name:

     @Html.DisplayFor(Function(model) model.VimsOrg.Phone, "Phone")
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!