Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use asp-for TagHelper combined with Reflection

I have a class Foo which contains a lot of properties, I'd like to iterate through all of them into a form. The website is built using ASP.NET Core 2.2 and Razor.

How can I build a MemberExpression that asp-for TagHelper seems to expect using Reflection? I've read a couple of post about this on the Forum but none of the answer fits my need.

The following snippet doesn't work.

@model Foo;
<h1>Foo Reflective filling example</h1>

    @foreach(var property in typeof(Foo).GetProperties()) {
        <p>
            <div class="row">
                <div class="col-md-3">
                    <label asp-for="@property.Name"></label> @*doesn't work!'*@
                </div>
                <div class="col-md-3">
                    <input asp-for="@property.Name" class="form-control" id="property.Name"/>
                    <span asp-validation-for="@property.Name" class="text-danger"></span>
                </div>
            </div>
        </p>
    }

Thanks for your help

like image 594
XavierAM Avatar asked Sep 06 '25 22:09

XavierAM


1 Answers

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.

Your code can be rewritten as below:

@foreach(var property in typeof(Foo).GetProperties()) {
    <p>
        <div class="row" >
            <div class="col-md-3">
                @Html.Label(@property.Name)
            </div>
            <div class="col-md-3">
                @Html.Editor(@property.Name,  new { htmlAttributes = new{ @class="form-control" } })
                @Html.ValidationMessage(@property.Name, new { htmlAttributes = new { @class="text-danger"} })
            </div>
        </div>
    </p>
}

Demo :

I create a custom Foo DTO as below :

public class Foo{
    public int Id {get;set;}
    public string Name {get;set;}
    public string Address {get;set;}
    public DateTime UpdatedAt{get;set;}
}

And the rendered form is :

enter image description here

like image 161
itminus Avatar answered Sep 08 '25 12:09

itminus