Search code examples
asp.net-mvcasp.net-mvc-3razormodeleditorformodel

Calling a child EditorTemplates from the Parent


Let's say I have a simple model:

public Vehicle {
    public int year;
}

And I have another model that extends from that:

public Car : Vehicle {
    public string make;
}

I have an EditorTemplate for Vehicle that allows you to set the year. It's stored in Views/Shared/EditorTemplates:

@model Vehicle
Year: @Html.EditorFor(m => m.year)

I want to create an EditorTemplate for a Car that calls the EditorTemplate for Vehicle, yet also adds in the ability to set the make. The idea being, if I decide to add more properties to Vehicle, I only have to change the Vehicle editor template. My Car editor template won't have to change.

I would have thought something like this would work:

@model Car
@Html.EditorForModel("Vehicle")
Make: @Html.EditorFor(m => m.make)

...but for whatever reason, it doesn't. My view is as simple as this:

@model Vehicle
@Html.EditorForModel()

That view does end up calling my Car template when I pass in a Car model, so that works. But the only thing that shows up is the editor for make. Nothing for year. Thus, the line @Html.EditorForModel("Vehicle") does not appear to do anything at all. It doesn't call the Vehicle EditorTemplate.

Any ideas? These are both editortemplates in /Views/Shared/EditorTemplates, and I wonder if that has anything to do with it. I tried @Html.EditorForModel("~/Views/Shared/EditorTemplates/Vehicle"), and appended a .cshtml to it, neither worked.


Solution

  • Got a workaround at least. I changed my view to:

    @model Vehicle
    @Html.EditorForModel("Vehicle")
    @Html.EditorForModel()
    

    and that works ok. It calls the Vehicle EditorTemplate, then the Car EditorTemplate. Not ideal, since it means every view I use Vehicle/Car in needs to do it. But at least it works.

    But why can't it call an EditorTemplate from the other EditorTemplate? It feels like a bug to me...