Search code examples
c#asp.net-mvcrazorasp.net-mvc-5.2

Receiving data type mismatch calling `EditorFor()`


When I call @Html.EditorFor() from a *.cshtml view, I am receiving the error:

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

That said, I am confident I am passing in a model of the correct type. My code looks something like this:

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

MyType is the model bound to each of my EditorTemplate pages. The value of the Template property corresponds to the names of EditorTemplate pages, and the value of the Field property maps to htmlField name (both return strings).

Based on the error, I would expect that Model.MyType is returning a Boolean value instead of a MyType value, but I have confirmed that is not the case. I can even write out @Model.MyType.GetType() and see it's correctly retrieving a MyType instance.


Solution

  • It's unintuitive, but this error will be thrown if the value for templateName doesn't map to a file name in the EditorTemplates directory. E.g., if Model.MyType.Template returns a string MyTemplate, but there isn't a corresponding ~/Views/Controller/EditorTemplates/MyTemplate.cshtml.

    In this particular case, there was an errant Model.MyType.Template value, which didn't map correctly to any EditorTemplates.

    I imagine a similar error will occur with DisplayFor().