c# - 使用 Blazor 将输入文本动态绑定(bind)到类/对象属性

标签 c# razor data-binding components blazor

我正在尝试使用 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/

相关文章:

c# - 如何将 Silverlight MVVM 中可观察集合中的单个字段数据绑定(bind)到组合框?

javascript - 绑定(bind)输入和非输入数字内容,用于计算一系列值

c# - 我应该在哪里找到 MVC Razor 中的共享@helper 函数

javascript - 用ajax提交后替换表单

c# - 如何计时从视频文件中显示和提取帧?

c# - 使用泛型可以将提供的类型限制为内置类型吗?

asp.net-mvc - 安装 MVC 4 后 Razor View 中没有智能感知 - 尝试了各种解决方案

c# - 在绑定(bind)到 ICommand 的 Button 处控制 ExceptionValidationRule

c# - 如何进行多线程安全的原子对象创建和交换

c# - 在windows phone项目中使用可移植类库