ASP.NET MVC 4 如何为字符串定义显示模板

9
我希望能为字符串属性创建一个显示模板,并对其他所有属性使用默认值。
我尝试在 Views/Shared/DisplayTemplates 中创建一个 string.cshtml 文件,其中包含以下内容:
@model string
@Html.TextBoxFor(m => m, new { @readonly = "readonly" })

我现在遇到了一个问题,当我尝试打开任何使用DisplayFor(m => m.property)的视图时,会显示错误,例如: The model item passed into the dictionary is of type 'System.DateTime', but this dictionary requires a model item of type 'System.String'. 或者: The model item passed into the dictionary is of type 'System.Int64', but this dictionary requires a model item of type 'System.String'。
我知道可以通过为每个使用的类型添加显示模板来解决这个问题,但我认为在未定义自定义模板的所有类型中使用“默认”模板也是可能的吗?
更新: 在Darin的回答后,我检查了Brad的教程并将模板更改为:
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @readonly = "readonly" })

这是基于“默认”模板的,适用于所有类型。
1个回答

12
有9个内置的展示模板: "Boolean", "Decimal", "EmailAddress", "HiddenInput", "Html", "Object", "String", "Text"和"Url"。 请参考以下博客文章,详细说明模板是如何工作以及如何解决模板。以下是其中的一句话摘录:
下面按顺序尝试以下模板名称:
  1. 从ModelMetadata中的TemplateHint
  2. 从ModelMetadata中的DataTypeName
  3. 类型的名称 (参见下面的注意事项)
  4. 如果对象不复杂: "String"
  5. 如果对象是复杂的并且是接口: "Object"
  6. 如果对象是复杂的而不是一个接口: 针对类型递归遍历继承层次结构,尝试每个类型名称
所以你在 DateTime 和 Int64 上使用了点4,因为这些类型没有默认模板。
因此,您可以使用 ModelMetadata 中的 Template hints 或 DataType names,仅针对视图模型上给定的属性使用此自定义模板。

1
你能告诉我在MVC源代码中Object或Collection.cshtml文件位于哪里吗? - Maslow
1
@Maslow:源代码中没有真正的cshtml文件,HTML是通过TagBuilder生成的(例如,请参见http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/8b17c2c49f88#src/System.Web.Mvc/Html/InputExtensions.cs) - Goran Obradovic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接