Reputation: 1928
I'm trying to use a list of string model property names to make a form. When using scaffolding code like this is generated:
@Html.HiddenFor(model => model.modelRecId)
I thought that using reflection could get the same results with code like this:
@Html.HiddenFor(model => model.GetType().GetProperty("modelRecId").GetValue(model, null))
Sadly c# doesn't like this syntax, yielding this error:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Any ideas on how to use the built-in html helpers given the property names as strings?
EDIT:
List<string> props = new List<string>();
props.Add("modelRecId");
props.Add("Name");
props.Add("Description");
//... etc
foreach (string prop in props)
{
@Html.LabelFor(Model.GetType().GetProperty(prop).GetValue(Model, null), prop)
@Html.EditorFor(Model.GetType().GetProperty(prop).GetValue(Model, null))
@Html.ValidationMessageFor(Model.GetType().GetProperty(prop).GetValue(Model, null))
}
The above code does not work. Is there a way to do something like this?
Upvotes: 0
Views: 452