接收数据类型不匹配调用 `EditorFor()`

Receiving data type mismatch calling `EditorFor()`

当我从 *.cshtml 视图调用 @Html.EditorFor() 时,我收到错误消息:

The model item passed into the dictionary is of type `System.Boolean', but this dictionary requires a model item of type 'MyType'.

也就是说,我相信我传递的是正确类型的模型。我的代码看起来像这样:

Html.EditorFor(m => m.MyType, Model.MyType.Template, Model.MyType.Field)

MyType 是绑定到我的每个 EditorTemplate 页面的模型。 Template 属性 的值对应 EditorTemplate 个页面的名称,Field 属性 的值映射到 htmlField 名称(均为 return 字符串)。

根据错误,我预计 Model.MyType 是 returning 一个 Boolean 值而不是 MyType 值,但我已经确认不是案子。我什至可以写出 @Model.MyType.GetType() 并看到它正在正确检索 MyType 实例。

这不直观,但如果 templateName 的值没有映射到 EditorTemplates 目录中的文件名,则会抛出此错误。例如,如果 Model.MyType.Template returns 一个字符串 MyTemplate,但没有相应的 ~/Views/Controller/EditorTemplates/MyTemplate.cshtml

在这种特殊情况下,有一个错误的 Model.MyType.Template 值,它没有正确映射到任何 EditorTemplates

我想 DisplayFor() 也会出现类似的错误。