DisplayFormat.DataFormatString for a phone number or social security number

39,939

Solution 1

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)

Solution 2

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")
    
Share:
39,939
AJ.
Author by

AJ.

I have a large beard, hence I am correct.

Updated on January 14, 2020

Comments

  • AJ.
    AJ. over 4 years

    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; }