I had some html that was being generated in multiple views in trying to keep up with DRY principles, I moved it into a Display Template.
Because the different views have different Models, how could I make the Display Template generic? The property names are the same.
Say I have these 2 models:
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;}
}
Here is my Display Template - How can I make this more generic - I need it to be able to accept any Model with the same property names?
@model ListModel
{
if(Model.Prop1)
{
<div>Prop1!</div>
}
if(Model.Prop2)
{
<div>Prop2!</div>
}
}
And these are my 2 views: List and Display
List:
@model ListModel
@DisplayFor(@Model, "CustomDisplayTemplate")
Display:
@model DisplayModel
@DisplayFor(@Model, "CustomDisplayTemplate") //will currently break as the custom display template expects a ListModel
Make an Interface with the two properties:
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;}
}
and afterwards use this interface as the model in your template
@model ISameModel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With