MVC Display Template for multiple models
asp.net-mvc, asp.net-mvc-5, razor
Solution
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
Problem
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 ```