ASP.NET MVC 4 define display template for string only
Asked Answered
I

1

9

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.

Idio answered 13/6, 2012 at 8:59 Comment(0)
A
12

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:

  1. TemplateHint from ModelMetadata
  2. DataTypeName from ModelMetadata
  3. The name of the type (see notes below)
  4. If the object is not complex: "String"
  5. If the object is complex and an interface: "Object"
  6. 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.

Acedia answered 13/6, 2012 at 9:23 Comment(2)
can you tell me where in the mvc source code the Object or Collection.cshtml files live?Orogeny
@Maslow: there is no really cshtml files in source code, html there is generated with help of TagBuilder (for example, see aspnetwebstack.codeplex.com/SourceControl/changeset/view/…)Idio

© 2022 - 2024 — McMap. All rights reserved.