Dynamic Display

August 30, 2019

How to display all the properties, when you don't know them - or don't care

Often, I have a need to display some data from a table. But I don;t want to go through the trouble of writing out a class (for intellisense) or writing for each, row, cell for every peoprty. If it's 5 properties - who cares? But 20? 30? 749?

Yeah - especially when it's a one-off what;s in this table  or testing scenario. 

I need to flesh this out and maybe even a small lib - but for now:

Reflection to the rescue. Basically, iterate over a collection, get the type, get the property and display. This also works with a dynamic types so you can do something like:

var list = NPoco.Database.FetchAsync<dynamic>("WHERE SQL IS COOL");

For the header/property/column  you get the property name. And then for the value you use getValue(). Below is for a single one, but it's similar for a list of items. Tahat's where the lib would help.

@foreach (var property in list.GetType().GetProperties())

                                        {

                                            try

                                            {

                                                <tr>

                                                    <td style="width:10px; white-space:nowrap;">@property.Name</td>

                                                    <td> @property.GetValue(Model.Tracker, null)</td>

 

 

                                                </tr>

                                            }

                                            catch { }

                                        }