我只想为字符串属性创建一个显示模板,并对所有其他属性使用默认值。
我尝试在 Views/Shared/DisplayTemplates 中制作一个包含以下内容的 string.cshtml:
@model string
@Html.TextBoxFor(m => m, new { @readonly = "readonly" })
现在,当我尝试打开任何使用 DisplayFor(m => m.property) 的 View 时遇到问题,它显示如下错误: 传递到字典中的模型项的类型为“System.DateTime”,但该字典需要类型为“System.String”的模型项。 或者: 传递到字典中的模型项的类型为“System.Int64”,但该字典需要“System.String”类型的模型项。
我知道我可以通过为使用的每种类型添加显示模板来解决此问题,但我认为也可以为未定义自定义模板的所有类型使用“默认”模板?
更新 在Darin的回答之后,我查看了Brad的教程并将模板更改为:
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @readonly = "readonly" })
这基于“默认”模板,适用于所有类型。
最佳答案
有 9 个内置显示模板:“Boolean”、“Decimal”、“EmailAddress”、“HiddenInput”、“Html”、“Object”、“String”、“Text”和“Url”。
看看 following blog post其中详细解释了模板的工作原理以及它们是如何解析的。以下是其中的一段引述:
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
对于 DateTime 和 Int64,您会遇到第 4 点,因为这些类型没有默认模板。
因此,您可以使用 ModelMetadata 中的模板提示或数据类型名称,仅将此自定义模板用于 View 模型上的给定属性。
关于razor - ASP.NET MVC 4 仅定义字符串的显示模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11011444/