mercredi 19 février 2020

Get all property names and values from a generic object C#

We have way too many tables on Index pages throughout our MVC app and we keep making more. I would like to come up with a way to handle any object that needs to be shown in a tabular form. My idea was to make the a partial view that takes in a collection of generic objects and then builds the table. I have figured out how I wan't to handle most of the front end, but striping the values off of this generic object has become a nightmare.

I simply want to access this object kinda like a list or array. I want to put the first prop value here .... and then the second here......I won't know what their names are and I really don't care to. Whatever the value, I just want to display it.

I am close. I know I am somewhat in the right place, but I have never used reflection besides with a container like autofac and I am out of my element.

@foreach (var item in Model.Collection)
{
    //TODO - figure out how to access values in generic object via reflection

    Type t = item.GetType();
    PropertyInfo prop = t.GetProperty("Id");
    var properties = t.GetProperties();
    var value = properties.First().ToString();

    Type[] typeParameters = t.GetGenericArguments();
    var r = t;

    List<string> values = new List<string>();

    Type myType = item.GetType();
    IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

    foreach (PropertyInfo ish in props)
    {
        object propValue = prop.GetValue(item, null);

        values.Add(propValue.ToString());
    }
}

![ ]1





Aucun commentaire:

Enregistrer un commentaire