问题
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>
.
回答1:
It comes to errors when I use @model List<dynamic>
as model of view.When I change it to @model dynamic
,it works with below code
@model dynamic
@using System.Reflection
@{
var properties = Model[0].GetType().GetProperties();
}
<table>
<tr>
@foreach (var item in properties)
{
<td>
@item.Name
</td>
}
</tr>
@foreach (var item in Model)
{
<tr>
@foreach (PropertyInfo p in properties)
{
<td>@p.GetValue(item)</td>
}
</tr>
}
</table>
回答2:
@model List<dynamic>
<table>
<tr>
@foreach (var item in Model.ElementAt(0).GetType().GetProperties())
{
<td>
@item.Name
</td>
}
</tr>
@foreach (var item in Model)
{
if (item.GetType() == typeof(Person))
{
var person = item as Person;
<tr>
@person.Name
</tr>
}
if (item.GetType() == typeof(Team)) {
var team = item as team;
<tr>
@team.Name
</tr>
}
}
</table>
来源:https://stackoverflow.com/questions/58107729/view-dynamic-model