Blazor 在 EditForm 中绑定一个 List<string>

Blazor binding a List<string> in an EditForm

我遇到了与 类似的问题,因为我无法让 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<T>(Expression<Func<T>> 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>

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

您要创建集合的双向数据绑定。

<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; }
}

} 

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