我正在尝试在视图中创建一个动态表,该表将根据我发送到该视图的模型类型而动态生成。所以,我基本上有两个动作:
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);
}
现在,我希望使用相同的视图来显示人员/团队列表,因此我不必重复该视图。我的Table.cshtml看起来像这样:
@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>
我的基本输出将是与下面显示的内容相对应的HTML表:
Id, PersonName, Age
1, John, 24
2, Mike, 32
3, Rick, 27
我有问题的是动态获取模型类实例中每个属性的值。我不知道如何从项目中获取价值(没有item.Property(someName).GetValue()
这样的东西)。这样,我可以发送一个列表(T可以是Person,Team,Student,任何东西),结果我会得到一个<table>
,其中包含Person / Team / Student属性(例如,Id,Name,Age)以及每个值其他<tr>
中的属性。
@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>