0

I have a class like this

public class Sample_Class {
    public string Property1 { get; set;}
    public string Property2 { get; set;}
}

and I want to have a html form like this:

<fieldset>
<legend>Change Password Form</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.Property1)
            @Html.TextBoxFor(m => m.Property1)
            @Html.ValidationMessageFor(m => m.Property1)
        </li>
        <li>
            @Html.LabelFor(m => m.Property2)
            @Html.TextBoxFor(m => m.Property1)
            @Html.ValidationMessageFor(m => m.Property1)
        </li>
    </ol>
    <input type="submit" value="Submit" />
</fieldset>

how can I do this dynamically? for example, like this:

....
    @foreach (property in Sample_Object.Properties) {
        <li>
            @Html.LabelFor(property)
            @Html.TextBoxFor(property)
            @Html.ValidationMessageFor(property)
        </li>
    }
....
3
  • You can use foreach such is shown in your above example. Are you wanting to create a partial-view instead? Commented Aug 3, 2015 at 17:49
  • @SamuelDavidson I prefer to have a partial-view, that get an Object and dynamically generate html form, based on Object's properties. Commented Aug 3, 2015 at 17:56
  • You don't have a collection property in your class. What it it that you want to achieve? Commented Aug 3, 2015 at 18:20

1 Answer 1

1

You can use the built-in EditorForModel function:

@model Sample_Class


@Html.EditorForModel()
<input type="submit" value="Submit" />

It essentially does what you want which is (according to the documentation)...

[Return] an HTML input element for each property in the model.

The downside of EditorForModel is that you lose fine-grained control over your markup. That being said, you can customize the output to a certain extent using model attributes and the various overloads.

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

Comments

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.