【发布时间】:2020-05-16 23:54:51
【问题描述】:
我正在使用 Blazor 从我的模型的属性创建一个动态表单。
我正在使用for each 循环来遍历模型的属性。
public class SensorType
{
public int Id { get; set; }
[Required]
[MaxLength(30)]
[Display(Name = "Sensor Type Name")]
public string Name { get; set; }
[Required]
[MaxLength(500)]
public string Description { get; set; }
[Required]
[MaxLength(2048)]
[Display(Name = "Datasheet URL")]
public string DatasheetUrl { get; set; }
}
我实现了这个剃刀视图,我尝试绑定到public SensorType sensortype { get; set; }。但我需要绑定到 sensortype.property,其中 property 是模型在 for each 循环中具有的任何属性。但我不能简单地打电话说@bind-Value="sensortype.property"。关于如何做到这一点的任何想法?我不想手动输入每个字段。谢谢!
<EditForm Model="@sensortype" OnValidSubmit="@SaveSensorType">
@foreach(var property in typeof(SensorType).GetProperties())
{
if(property.Name == "Id")
{
continue;
}
<div class="form-group row">
<label class="col-sm-2 col-form-label">@(GetAttribute(property, false)) </label> //This function get the name of the property in a human-readable way.
<div class="col-sm-10">//I would like to bind here to sensortype's property in the for each loop but sensortype.property gives me an error.
<InputTextArea class="form-control" @bind-Value="sensortype.property" value="sensortype.property.Name" placeholder="Description of the Type of Sensor" />
</div>
</div>
}
【问题讨论】:
-
你不应该那样做……而且你不能那样做。 FieldIdentifier 仅支持对象的简单成员访问器(字段、属性)。 "
sensortype.property"没有意义。没有这样的东西......你会得到一个错误。 -
是的,sensor.property 是没有意义的,但它只是为了让我知道如果它有意义的话我想做什么。
标签: c# asp.net asp.net-core blazor blazor-server-side