简体   繁体   中英

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.

For display template is not getting hit, you need to copy the template to output folder by setting Copy to Output Directory .

Follow steps below:

  1. @Html.DisplayFor and @model PFDTrustDomain.Client are mismatch, template expected Client, but you pass string with SSN. Change @Html.DisplayFor like @Html.DisplayFor(model => model.SSN,"SSN")
  2. Change @model PFDTrustDomain.Client in template to below

     @model string <div> @Model.Insert(3, "-").Insert(6, "-"); </div> 
  3. Set Copy to Output Directory for Shared/DisplayTemplates/SSN.cshtml to Copy always

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM