如何将ASP-for TagHelper与反射结合使用 [英] How to use asp-for TagHelper combined with Reflection
问题描述
我有一个 Foo 类,其中包含很多属性,我想将所有这些属性迭代为一种形式.该网站是使用ASP.NET Core 2.2和Razor构建的.
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.
如何使用反射功能为TagHelper的asp生成一个MemberExpression?我已经在论坛上阅读了几篇关于此的文章,但没有一个答案符合我的需求.
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.
以下代码段无效.
@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>
}
感谢您的帮助
推荐答案
InputTagHelper帮助我们以声明性编程风格编写代码.如果您发现难以通过反射动态渲染不同的字段,请随时以编程的方式使用 @ Html.Xyz
等效项.
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>
}
演示:
我创建一个自定义的Foo DTO,如下所示:
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;}
}
呈现的形式是:
这篇关于如何将ASP-for TagHelper与反射结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!