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?

1
  • How are you currently invoking the view in your controller?
    – Ben
    May 16, 2019 at 23:35

1 Answer 1

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()
1
  • 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? May 17, 2019 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.