C# reflection use variable as object.[var]

前端 未结 2 997
粉色の甜心
粉色の甜心 2021-01-22 03:12

I\'m trying to generate a table in a razor view using reflection to pull the properties from the model.

Here is what I\'ve tried:

@if (@Model.Count() &         


        
相关标签:
2条回答
  • 2021-01-22 03:39

    If you dont really need the DisplayFor method, you can do it like this in your loop:

    <tbody>
                @foreach (PCNWeb.Models.Switch item in Model)
                {
                    /*System.Reflection.PropertyInfo[]*/ properties = item.GetType().GetProperties();
                    <tr>
                    @foreach (var property in properties)
                    {                    
                        <td>
                            @property.GetValue(item,null)
                        </td>
                    }
                    </tr>
    
                }
            </tbody>
    
    0 讨论(0)
  • 2021-01-22 03:56

    So basically I need to access the value of a property of item based on the name of the property stored in a variable.

    No, you need to access the value of a property based on a PropertyInfo object describing it. That's far far easier.

    property.GetValue(item)
    
    0 讨论(0)
提交回复
热议问题