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

2

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?

Tagore answered 11/11, 2013 at 20:46 Comment(4)
Why would you not just use Html.Label(prop.Name) and @Html.ValidationMessage(prop.Name)?Hejaz
Does this still use the attributes on the model for validations? like [Required]Tagore
Yeah it uses the same method in the end. The For methods just use linq expressions to pull the property name.Hejaz
I think you'd have to create the Expression<Func<TModel, TProperty>> 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...Treen
S
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/

Speedwell answered 12/11, 2013 at 21:28 Comment(0)
E
0

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

@Html.ValidationSummary()
Ellingson answered 12/11, 2013 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.