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>
}
....
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.