简体   繁体   English

循环模型数据并将其列出

[英]Loop model data and list it out

I am trying to loop through data that is passed to my view in a model object. 我试图遍历传递到模型对象中视图的数据。 I want to list out the property name and the property value of each of the model properties, even if they are null. 我想列出每个模型属性的属性名称和属性值,即使它们为null。 I have been at this for a few hours and have tried googling it but cannot get any good examples that work. 我已经在这里呆了几个小时,并尝试使用Google进行搜索,但是无法获得任何有效的示例。

I got this to list out all of the properties of the current object, however cannot get the values: 我得到这个列出了当前对象的所有属性,但是无法获取值:

 @model List<object>
 @foreach (var obj in Model)
 {
  var properties = obj.GetType().GetProperties();
  foreach (var property in properties)
   {
    string name = null;
    var value = ""
    try
    {
         name = property.Name;
        value = property.GetType().GetProperty(property.Name).GetValue(property, null).ToString();
    }
    catch (Exception e)
    {
        <p>@e</p>

    }
    finally
    {
        <p>@name - @value</p>
    }

}

And the controller code: 和控制器代码:

            RootobjectPlayerData obj = JsonConvert.DeserializeObject<RootobjectPlayerData>(jsonstring);
            List<object> list = new List<object>();
            list.Add(obj.data.accountinfo);
            list.Add(obj.data.accountinfo.statistics);
            list.Add(obj.data.accountinfo.statistics.clan);
            list.Add(obj.data.accountinfo.statistics.company);
            list.Add(obj.data.accountinfo.statistics.all);
            list.Add(obj.data.accountinfo.statistics.historical);
            list.Add(obj.data.accountinfo.statistics.team);
            return View(list);

I am able to do a break point and view all of the data within each of the objects, however I cannot get it to print out on screen. 我可以做一个断点并查看每个对象中的所有数据,但是无法在屏幕上打印出来。

First of all you are getting the property value incorrectly. 首先,您错误地获得了属性值。 You should get the value from the object you have, but not from the type of the property: 您应该从拥有的对象中获取值,而不是从属性的类型中获取值:

value = obj.GetType().GetProperty(property.Name).GetValue(obj, null)

Secondly, try to loop only through data that's not null: 其次,尝试仅遍历不为空的数据:

@foreach (var obj in Model.Where(w => w != null))

Try getting the values from i , not x . 尝试从i而不是x获得值。

try
{
     name = x.Name;
    // Wrong
    // value = x.GetType().GetProperty(x.Name).GetValue(x, null).ToString();
    // Correct
    value = x.GetValue(i, null).ToString();
}
catch (Exception e)
{
    <p>@e</p>

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM