Is there a way I can use the DisplayFormat attribute on a view model property to apply a DataFormatString format for a social security number or a phone number? I know I could do this with javascript, but would prefer to have the model handle it, if possible.

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

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:

<!-- language: lang-vb -->
@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:

    <!-- language: lang-vb -->
     <DataType("Phone")> _
     Public Property Phone As String
    

    And then call using a simple DisplayFor:

    <!-- language: lang-vb -->
      @Html.DisplayFor(Function(model) model.Phone)
    
  2. Alternatively, you can specify the DisplayTemplate you'd like to use by name:

    <!-- language: lang-vb -->
      @Html.DisplayFor(Function(model) model.VimsOrg.Phone, "Phone")