Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through Model properties in reflection, then use Html helpers to display. How to get concrete property back?

We have an MVC4 ASP.Net site that we are trying to use reflection to loop through properties of a model, and display the names/values/and other information using Html helpers.

We have a custom Html Helper that we are passing in arguments from the method below.

@foreach (PropertyInfo prop in Model.GetType().GetProperties())
{
    <div class="form-group">
        Html.LabelFor( ?? Any ideas ?? )
        <div class="col-sm-9">
            @SuperEditorFor.ReflectiveEditorFor(prop, Model)
            @Html.ValidationMessageFor(model => model.GetType().GetProperty(prop.Name))
        </div>
    </div>
}

We have tried putting in the "property" (quote) as in the ValidationMessageFor but as we suspected, it wants the actual concrete property, not the reflection propertyInfo object.

Does anyone know if this is possible? Has anyone tried to do this before?

like image 214
SnareChops Avatar asked Nov 11 '13 20:11

SnareChops


1 Answers

You don't need to use generic implementations for that (EditorFor, DisplayFor...), just use the non generic ones, Editor, Display...

This will work just fine, you will get validation, automatic bindings and everything else, the whole nine yards...

@foreach (PropertyInfo prop in Model.GetType().GetProperties())
{
    <div class="form-group">
        @Html.Label(prop.Name)
        <div class="col-sm-9">
            @Html.Editor(prop.Name)
            @Html.ValidationMessage(prop.Name)
        </div>
    </div>
}

If you want to experiment with generic implementations here is a great blog post on how to do that

http://www.joelscode.com/use-mvc-templates-with-dynamic-generated-types-with-custom-htmlhelper-extensions/

like image 188
Davor Zlotrg Avatar answered Nov 14 '22 22:11

Davor Zlotrg