0

I have a Model:

public class Dog: IPet
{
    // IPet Implementation
    public string Name { get; set; }
}

and a DisplayTemplate in DisplayTemplates/Dog.cshtml

@model IPet // note this is the interface, not the concrete Dog
<label>@Model.Name</label>

This works perfectly until I rename the file to IPet.cshtml; then the binding fails. I want to use the same DisplayTemplate for Dog, Cat, Rat, Goat and Gnu, all of which are implementations of IPet.

How can I get the binding to work?

Scott Baker
  • 10,013
  • 17
  • 56
  • 102

1 Answers1

2

By default, the name of the view is the name of an object type that passed to template-helper. So need to explicitly define the template name:

@Html.DisplayFor(x => x.Dog, "IPet")

When need to render the model that contains IPet instances use UIHint-attribute:

public partial class Zoo
{
    [UIHint("IPet")]
    public Dog Dog;

}

Template:

@model Zoo
@Html.DisplayForModel()
vladimir
  • 13,428
  • 2
  • 44
  • 70
  • Is there any way to customize the view creator (whatever that is) to check for the type declared as the `@model` _first_, then fallback to the default method of finding a display template? – Scott Baker May 17 '19 at 16:38