Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 define display template for string only

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.

like image 496
Goran Obradovic Avatar asked Jun 13 '12 08:06

Goran Obradovic


1 Answers

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.

like image 185
Darin Dimitrov Avatar answered Nov 06 '22 09:11

Darin Dimitrov