Hi @Dean Marinov,
The InputTagHelper helps us to write code in a style of declarative programming. When you find it difficult to render different fields dynamically by reflection, feel free to use the @Html.Xyz
equivalent in a programmatic way:
@model Person
<form>
@foreach (var property in typeof(Person).GetProperties())
{
<div class="form-group">
@Html.Label(@property.Name)
@Html.Editor(@property.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessage(@property.Name, new { htmlAttributes = new { @class = "text-danger" } })
</div>
}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Or you can manually set the value for label and change the input tag helper like below. Due to the @property.Name
contains the value so that it will display the value. You need get the property real value and set to asp-for
. Then for model binding, be sure manually add the name
attribute. id
attribute is optional by yourself.
@model Person
<form>
@foreach (var property in typeof(Person).GetProperties())
{
var propValue = @property.GetValue(@Model, null);
<div class="form-group">
<label asp-for="@property.Name" class="control-label">@property.Name</label>
<input asp-for="@propValue" name="@property.Name" id="@property.Name" class="form-control" />
</div>
}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Feel free to choose each one you like to achieve your requirement.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Rena