如果为接口命名,则 MVC DisplayTemplate 不呈现
MVC DisplayTemplate Not Rendering if Named for Interface
我有一个模型:
public class Dog: IPet
{
// IPet Implementation
public string Name { get; set; }
}
和 DisplayTemplates/Dog.cshtml
中的显示模板
@model IPet // note this is the interface, not the concrete Dog
<label>@Model.Name</label>
在我将文件重命名为 IPet.cshtml
之前,这一切都很好;然后绑定失败。我想对 Dog
、Cat
、Rat
、Goat
和 Gnu
使用相同的 DisplayTemplate,所有这些都是 IPet
的实现。
如何使绑定生效?
默认情况下,视图的名称是传递给 template-helper 的对象类型的名称。所以需要显式定义模板名称:
@Html.DisplayFor(x => x.Dog, "IPet")
当需要渲染包含IPet实例的模型时使用UIHint-attribute:
public partial class Zoo
{
[UIHint("IPet")]
public Dog Dog;
}
模板:
@model Zoo
@Html.DisplayForModel()
我有一个模型:
public class Dog: IPet
{
// IPet Implementation
public string Name { get; set; }
}
和 DisplayTemplates/Dog.cshtml
@model IPet // note this is the interface, not the concrete Dog
<label>@Model.Name</label>
在我将文件重命名为 IPet.cshtml
之前,这一切都很好;然后绑定失败。我想对 Dog
、Cat
、Rat
、Goat
和 Gnu
使用相同的 DisplayTemplate,所有这些都是 IPet
的实现。
如何使绑定生效?
默认情况下,视图的名称是传递给 template-helper 的对象类型的名称。所以需要显式定义模板名称:
@Html.DisplayFor(x => x.Dog, "IPet")
当需要渲染包含IPet实例的模型时使用UIHint-attribute:
public partial class Zoo
{
[UIHint("IPet")]
public Dog Dog;
}
模板:
@model Zoo
@Html.DisplayForModel()