Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
I'm not sure there is a way to do it using the built in HtmlHelper methods; however, you could certainly write your own HtmlHelper extension method to do this for you. – shuniar 11 hours ago
add comment (requires an account with 50 reputation)

1 Answer

up vote 1 down vote accepted

Simply @Html.Hidden("SomeProperty")

share|improve this answer
Hey @max, Not sure how this solves the problem. I've edited my question, does that make my goal any clearer? – TechplexEngineer 12 hours ago
@TechplexEngineer Sorry, I thought Model.modelRecId had the property name, see my updated answer. – Max Toro 12 hours ago
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.