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:
-
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)
-
Alternatively, you can specify the DisplayTemplate you'd like to use by name:
<!-- language: lang-vb -->
@Html.DisplayFor(Function(model) model.VimsOrg.Phone, "Phone")