我正在尝试使用 Blazor 为类中的属性构建输入字段的动态列表,但无法弄清楚如何将输入框的内容绑定(bind)/链接到类的属性。 (这个类可以有大量的公共(public) Prop ,不仅仅是下面例子中的名称和描述,它们并不总是“字符串”类型)
假设我有这个类/模型:
public class customer{
public string Name { get; set; }
public int Age { get; set; }
public string Description { get; set; }
}
我得到了这个 blazor 组件( updateC.razor ):
@inherits CLogic
@if (nfo != null)
{
@foreach (var obj in nfo)
{
<input type="text" class="form-control"
bind=@SCustomer.GetType().GetProperty(obj.ToString())/>
}
}
最后是 Clogic:
public class Clogic: ComponentBase{
[Parameter]
public Customer SCustomer { get; set; } = new Customer();
[Parameter]
public PropertyInfo[] nfo { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
nfo = SCustomer.GetType().GetProperties();
StateHasChanged();
}
}
}
这假设将每个输入字段中所做的更改绑定(bind)到 SCustomer 的当前实例中的正确属性(当输入时,假设更新类/对象的正确属性)。这不起作用,SCustomer 内部的值在输入完成后不会更改。我猜我完全错了,但似乎无法弄清楚如何使这项工作,也找不到任何这样做的例子。
最佳答案
@foreach (var propertyInfo in nfo)
{
<input type="text" class="form-control"
value="@propertyInfo.GetValue(SCustomer)"
@onchange="@((ChangeEventArgs __e) =>
propertyInfo.SetValue(SCustomer, __e.Value.ToString()))" />
}
关于c# - 使用 Blazor 将输入文本动态绑定(bind)到类/对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60323160/