MVC View that will display attributes of any Model

So I spend a lot of time creating simple internal apps that aren't pretty, but are great for giving people (me) access to data without query analyzer, very simple apps in short.  I hate it when I have to update these simple apps though, and if you create enough of them, objects in the system are always changing and you end up wasting a lot of time updating views to show the new data.  
To help this, I devised a bit of code to put in your view that will render a model for ever, updating even if the object changes.  Lets check it out.
<div class="fieldgrid" style="float:left;">
            <table class=" table-bordered" style="max-width:200px;word-wrap: break-word;">
                @{int i = 20; }
                @foreach (var prop in Model.GetType().GetProperties().Where(c => !c.PropertyType.ToString().Contains("Collections.Generic")).OrderBy(c => c.Name))
                    if (i == 0)
                        i = 20;
                    @:<div class="fieldgrid" style="float:left;"><table class=" table-bordered" style="max-width:200px;word-wrap: break-word;">
                            <td class="display-label">
                                @prop.GetValue(Model, null)
So whats going on isn't pretty, but basically I am reflecting my model, and the looping through its properties and displaying them in alphabetical order.  I also try to weed out the complex types in the where clause as you can see.  This did get a bit more complex because I wanted to split them into smaller tables so they don't get too huge, that's where the if block comes in.  But really, a rather simple, and powerful way to display a model dynamically.

Add comment