Search code examples
c#asp.net-corerazor-pagesdisplay-templates

Razor Page Display Template for SSN stored as a Varchar(9)


I am trying to display SSN stored as Varchar(9) with dashes.

The SSN in the database is stored as a varchar(9), with no dashes. It is not stored as a numeric because any leading zeros are dropped if it is stored as a numeric. I cannot use the DisplayFormat attribute with DataFormatString = "{0:###-##-####}" because that seems to only work if SSN is stored as a Long type. So, I am trying to create a Display Template for it. I have created a .cshtml file called SSN and placed it in a folder called DisplayTemplates inside the Shared folder, and I am using @Html.DisplayFor(modelItem => item.SSN) on the Razor Pages to display the SSN, but the mask that I created in the display template does not take effect.

Here is the code in the SSN.cshtml display template:

@model PFDTrustDomain.Client

<div>
    @Model.SSN.Insert(2, "-").Insert(5, "-");
</div>

I expect the SSN to display like: 123-45-6789, but is continues to display like: 123456789.


Solution

  • I've found the issue (with the sage help of my mentor). In addition to changing the character positions to 3 and 6, as recommended by madreflection, it was necessary to add the string "Name of display template" into the DisplayFor method in the .cshtml file, like so:

        <td>
            @Html.DisplayFor(modelItem => item.SSN, "SSN")
        </td>