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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With