Okay, I have been looking for a resolution for this simple task all day.
I have an mvc model class which has a BIC property and a NationalNumber property. Bother are string values. I want to use a DisplayFor helper to render the property on the view BUT, with a formatting applied.
for completeness: the formatting for the NationalNumber is '00.00.00-000.00' , the formatting for BIC is AAAA BB CC
I tried annotating my properties with a DisplayFormat Attribute, but that only seems to work with DateTimes, numeric values, etc,..
[DisplayFormat(DataFormatString = "{0:##.##.##-###.##}")]
Then I looked at creating a custom DisplayFormat attribute , but that also works with patterns that apply to DateTimes, numeric values, etc.. You still need to suppy a DataFormatString value in the constructor of your custom attribute. But the filter does not seem to work with strings!
For the moment I ended up doing the markup clientSide(with a mask plugin) but that's not really what I want!
To summarize: I want to use @Html.DisplayFor(x=>x.BicNumber)
and have it rendered with a custom formatting, preferrably annotaded on my viewmodel, with BicNumber being a string.
Thanks in advance
If your NationalNumber
and BIC
were separate data types, you could create display templates , store them under ~/Views/Shared/DisplayTemplates/NationalNumber.cshtml
and ~/Views/Shared/DisplayTemplates/BIC.cshtml
, and it would then automatically work as you want.
If you want to keep these properties as strings, the automatic approach won't work for you because a display template created for string.cshtml
would affect all strings in the project.
So create a display template named ~/Views/Shared/DisplayTemplates/NationalNumber.cshtml
, where you would manually output parts of the number:
@model string
@String.Format("{0}.{1}.{2}-{3}.{4}", Model.Substring(0, 2), Model.Substring(2, 2), Model.Substring(4, 2), Model.Substring(6, 3), Model.Substring(9, 2))
(note the capitalized String
, it is important ) and specify it explicitly:
@Html.DisplayFor(x=>x.NationalNumber, "NationalNumber")
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.