I want to create a display template for string properties only, and use default for all others.
I tried to make a string.cshtml in Views/Shared/DisplayTemplates with following contents:
@model string
@Html.TextBoxFor(m => m, new { @readonly = "readonly" })
I now have a problem when I try to open any view which uses DisplayFor(m => m.property), it shows error like: The model item passed into the dictionary is of type 'System.DateTime', but this dictionary requires a model item of type 'System.String'. or: The model item passed into the dictionary is of type 'System.Int64', but this dictionary requires a model item of type 'System.String'.
I know that I can solve this by adding display template for every type used, but I suppose that it is also possible to use "default" template for all types where custom template is not defined?
UPDATE After Darin's answer, I checked Brad's tutorial and changed template into:
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @readonly = "readonly" })
This is based on "default" template and works for all types.
There are 9 built-in display templates: "Boolean", "Decimal", "EmailAddress", "HiddenInput", "Html", "Object", "String", "Text", and "Url".
Take a look at the following blog post which explains in details how templates work and how are they resolved. Here's a quote from it:
The following template names are tried in order:
- TemplateHint from ModelMetadata
- DataTypeName from ModelMetadata
- The name of the type (see notes below)
- If the object is not complex: "String"
- If the object is complex and an interface: "Object"
- If the object is complex and not an interface: Recurse through the inheritance hiearchy for the type, trying every type name
So you are hitting point 4. for DateTime and Int64 because there's no default template for those types.
So you could use Template hints or DataType names from the ModelMetadata to use this custom template only for given properties on your view model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With