C# 视图-动态模型
我试图在视图中创建一个动态表,该表将根据我发送到视图的模型类型动态生成。所以,我基本上有两个动作:C# 视图-动态模型,c#,asp.net-mvc,asp.net-core,model-view-controller,view,C#,Asp.net Mvc,Asp.net Core,Model View Controller,View,我试图在视图中创建一个动态表,该表将根据我发送到视图的模型类型动态生成。所以,我基本上有两个动作: public-IActionResult-People() { List lst=新列表(); //添加数据。。。 返回视图(“表”,lst); } 公共成果小组() { List lst=新列表(); //添加数据。。。 返回视图(“表”,lst); } 现在我希望有相同的视图来显示人员/团队的列表,这样我就不必重复它了。My Table.cshtml如下所示: @model List<
public-IActionResult-People()
{
List lst=新列表();
//添加数据。。。
返回视图(“表”,lst);
}
公共成果小组()
{
List lst=新列表();
//添加数据。。。
返回视图(“表”,lst);
}
现在我希望有相同的视图来显示人员/团队的列表,这样我就不必重复它了。My 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>
我的问题是动态获取模型类实例中每个属性的值。我不知道如何从项中获取值(没有item.Property(someName).GetValue()
)。通过这种方式,我可以发送一个列表(T可以是个人、团队、学生、任何东西),结果我将得到一个带有个人/团队/学生属性(例如Id、姓名、年龄)的
,以及另一个@模型列表中每个属性的值
@foreach(Model.ElementAt(0.GetType().GetProperties()中的变量项)
{
@项目名称
}
@foreach(模型中的var项目)
{
if(item.GetType()==typeof(Person))
{
var person=项目作为人员;
@人名
}
if(item.GetType()==typeof(Team)){
var团队=项目作为团队;
@团队名称
}
}
当我使用@model List
作为视图模型时出现错误。当我将其更改为@model dynamic
时,它使用以下代码
@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>
@模型动态
@使用系统反射
@{
变量属性=模型[0]。GetType().GetProperties();
}
@foreach(属性中的变量项)
{
@项目名称
}
@foreach(模型中的var项目)
{
@foreach(PropertyInfo p in properties)
{
@p、 GetValue(项目)
}
}
可能的重复项您是否能够显示列名?
@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>
@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>