I am attempting to create a dynamic table in my view that will be dynamically generated depending on the type of model I send to the view. So, I basically have two actions:
public IActionResult People()
{
List<Person> lst = new List<Person>();
// Add data...
return View("Table", lst);
}
public IActionResult Teams()
{
List<Team> lst = new List<Team>();
// Add data...
return View("Table", lst);
}
Now I would like to have the same view that will show a list of people / teams, so that I don't have to duplicate it. My Table.cshtml looks like this:
@model List<dynamic>
<table>
<tr>
@foreach (var item in Model.ElementAt(0).GetType().GetProperties())
{
<td>
@item.Name
</td>
}
</tr>
@foreach (var item in Model)
{
<tr>
// foreach (var propValue in item.GetProperties())
// Get value for each property in the `item`
</tr>
}
</table>
My basic output would be an HTML table corresponding to what is shown below:
Id, PersonName, Age
1, John, 24
2, Mike, 32
3, Rick, 27
What I have a problem with is dynamically get the value for each property in my model class instance. I don't know how to get the value from the item (there's no such thing as item.Property(someName).GetValue()
). That way I could send a List (T could be Person, Team, Student, anything) and as a result I would get a <table>
with Person / Team / Student properties (e.g Id, Name, Age) and values of each of the properties in another <tr>
.