7

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?

SnareChops
  • 13,175
  • 9
  • 69
  • 91
  • 1
    Why would you not just use `Html.Label(prop.Name)` and `@Html.ValidationMessage(prop.Name)`? – jones6 Nov 11 '13 at 21:35
  • Does this still use the attributes on the model for validations? like `[Required]` – SnareChops Nov 12 '13 at 14:46
  • Yeah it uses the same method in the end. The For methods just use linq expressions to pull the property name. – jones6 Nov 12 '13 at 16:53
  • 1
    I think you'd have to create the `Expression>` the LabelFor() and ValidationMessageFor() expect manually in order for this to work. Not impossible. A larger concern is how fast the page will render with all of that reflection going on... – Heretic Monkey Nov 12 '13 at 20:23

2 Answers2

8

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/

Red
  • 818
  • 2
  • 14
  • 26
Davor Zlotrg
  • 6,020
  • 2
  • 33
  • 51
0

I believe that's not possible the way you want it. Try to use this instead :

@Html.ValidationSummary()
Oualid KTATA
  • 1,116
  • 10
  • 20