I hope this makes as much sense as I think it does!
As List<PersonModel>
, List<EmployeeModel>
and List<StudentModel>
are actually considered completely different, you will need a way to overcome that issue. I use a generic container class:
public interface IGenericContainer
{
dynamic Data { get; }
}
public class GenericContainer<T> : IGenericContainer
{
T _Data { get; set; }
public GenericContainer(T data)
{
_Data = data;
}
dynamic IGenericContainer.Data
{
get { return _Data; }
}
}
public class GenericContainer
{
public static GenericContainer<T> Create<T>(T data)
{
return new GenericContainer<T>(data);
}
}
You then need a generic view that uses this. Put this in Shared/DisplayTemplates/GenericGrid.cshtml
@using System.Reflection;
@using System.Text;
@{
Layout = null;
}
@model IGenericContainer
@{
IEnumerable<PropertyInfo> properties = null;
if (Model.Data.Count > 0)
{
properties = Model.Data[0].GetType().GetProperties();
}
}
<div>
@if (properties != null)
{
<table>
<thead>
<tr>
@foreach (var prop in properties)
{
<td>@prop.Name</td>
}
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Data.Count; i++)
{
<tr>
@foreach (var prop in properties)
{
<td>@prop.GetValue(Model.Data[i])</td>
}
</tr>
}
</tbody>
</table>
}
</div>
To use this you will need to add this to your view:
@Html.DisplayFor(m => GenericContainer.Create(Model.PersonList), "GenericGrid")
And PersonList is a property in your model of type List<PersonModel>
or a list of any of your models.