【问题标题】:Blazor binding a List<string> in an EditFormBlazor 在 EditForm 中绑定 List<string>
【发布时间】:2022-01-19 10:24:10
【问题描述】:

我有一个与 this question 类似的问题,因为我无法让 Blazor EditForm 绑定到简单的列表。

为了将 List 绑定到 EditForm,我是否遗漏了什么?

Person.cs

public class Person {
  public List<string>? Names { get; set; }
}

EditForm1.razor 产生编译时错误:Cannot assign to 'item' because it is a 'foreach iteration variable'。我明白了 - 迭代器是只读的,所以我可以理解。

<EditForm Model="@person">
  @if (person is not null) {
    @if (person.Names is not null) {
      @foreach (var item in person.Names) {
        <InputText @bind-Value="@item" />
      }
    }
  }
</EditForm>

所以,按照referenced Microsoft documentation,我重构了它。

EditForm2.razor 编译并运行...直到 person.Names 实际上有一个值。然后它抛出ArgumentException: The provided expression contains a InstanceMethodCallExpression1 which is not supported. FieldIdentifier only supports simple member accessors (fields, properties) of an object. Microsoft.AspNetCore.Components.Forms.FieldIdentifier.ParseAccessor&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; accessor, out object model, out string fieldName)

<EditForm Model="@person">
  @if (person is not null) {
    @if (person.Names is not null) {
      @for (int x = 0; x < person.Names.Count; x++) {
        <InputText @bind-Value="@person.Names[x]" />
      }
    }
  }
</EditForm>

EditForm3.razor 是我最后一次尝试。这会编译和渲染,但是一旦我尝试使用编辑框做任何事情,应用程序就会崩溃并显示Unhandled exception rendering component: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')。我 99% 确定这种方法是错误的,但我现在正抓着稻草。

<EditForm Model="@person">
  @if (person is not null) {
    @if (person.Names is not null) {
      @for (int x = 0; x < person.Names.Count; x++) {
        <input @bind="@person.Names[x]" />
      }
    }
  }
</EditForm>

【问题讨论】:

    标签: c# blazor blazor-server-side


    【解决方案1】:

    答案在您链接到的已接受答案中...

    您正在寻找创建集合的双向数据绑定。

    <EditForm Model="@person">
        @foreach (var PName in person.names) 
        {
            <InputText @bind-Value="@PName.Name" />
        }
     </EditForm>
    
    @code
    {
    private Person person = new Person {ID = "1", names = new List<PersonName>() 
                    { new PersonName {Name = "Marry" }, 
                      new PersonName {Name = "Marria" } 
                    };
    
    public class Person
    {
       public string ID {get;set;}
       public List<PersonName> names { get; set; }
    }
    
    public class PersonName 
    {
        public string Name { get; set; }
    }
    
    } 
    

    请注意,为了绑定 Name 属性,您必须在它自己的类中定义它,并在 Person 模型中定义该类的列表 ( PersonName )。这是绑定到集合的唯一方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多