0

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?

1
  • 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. Commented Jul 26, 2013 at 17:48

1 Answer 1

1

Simply @Html.Hidden("SomeProperty")

Sign up to request clarification or add additional context in comments.

2 Comments

Hey @max, Not sure how this solves the problem. I've edited my question, does that make my goal any clearer?
@TechplexEngineer Sorry, I thought Model.modelRecId had the property name, see my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.