视图-动态模型 [英] View - dynamic model

查看:63
本文介绍了视图-动态模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在视图中创建一个动态表,该表将根据发送到该视图的模型类型而动态生成.所以,我基本上有两个动作:

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);
}

现在,我希望使用相同的视图来显示人员/团队列表,因此我不必重复该视图.我的Table.cshtml看起来像这样:

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>

我的基本输出将是与下面显示的内容相对应的HTML表:

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

我遇到的问题是动态获取模型类实例中每个属性的值.我不知道如何从项目中获取值(没有 item.Property(someName).GetValue()这样的东西).这样,我可以发送一个列表(T可以是Person,Team,Student,任何东西),结果我会得到一个包含Person/Team/Student属性(例如,Id,Name)的< table> ,年龄)和另一个< tr> 中的每个属性的值.

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>.

推荐答案

当我使用 @model List< dynamic> 作为视图模型时出现错误.将其更改为@model动态,可与以下代码配合使用

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>

这篇关于视图-动态模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆