我有一些html是在多个视图中生成的,试图跟上DRY原则,我将其移动到显示模板中。
因为不同的视图有不同的模型,我怎么能使显示模板通用?属性名称相同。
说我有这两个型号:
public class ListModel
{
public bool Prop1 {get;set;}
public bool Prop2 {get;set;}
}
public class DisplayModel
{
public bool Prop1 {get;set;}
public bool Prop2 {get;set;}
}
这是我的显示模板 - 如何使其更通用 - 我需要它能够接受任何具有相同属性名称的模型?
@model ListModel
{
if(Model.Prop1)
{
<div>Prop1!</div>
}
if(Model.Prop2)
{
<div>Prop2!</div>
}
}
这些是我的2个观点:列表和显示
列表:
@model ListModel
@DisplayFor(@Model, "CustomDisplayTemplate")
显示:
@model DisplayModel
@DisplayFor(@Model, "CustomDisplayTemplate") //will currently break as the custom display template expects a ListModel
答案 0 :(得分:5)
使用两个属性创建一个接口:
public interface ISameModel
{
bool Prop1 { get; }
bool Prop2 { get; }
}
public class ListModel : ISameModel
{
public bool Prop1 {get;set;}
public bool Prop2 {get;set;}
}
public class DisplayModel : ISameModel
{
public bool Prop1 {get;set;}
public bool Prop2 {get;set;}
}
然后将此界面用作模板中的模型
@model ISameModel
答案 1 :(得分:3)
一种选择是使用UIHint
属性。将此属性添加到模型属性后,Razor将查找具有相同名称的视图模板。
[UIHint("MyCustomView")]
public class ListModel
{
public bool Prop1 {get;set;}
public bool Prop2 {get;set;}
}
[UIHint("MyCustomView")]
public class DisplayModel
{
public bool Prop1 {get;set;}
public bool Prop2 {get;set;}
}
您可以将自定义视图放在Views/DisplayTemplates/MyCustomView.cshtml
,请注意模型类型现在是动态的:
@model dynamic
@if(Model.Prop1)
{
<div>Prop1!</div>
}
@if(Model.Prop2)
{
<div>Prop2!</div>
}
您还可以在Views/EditorTemplates/MyCustomView.cshtml
添加编辑器模板的视图。