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?
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()