Blazor 在<string>编辑窗体中绑定列表



我有一个类似于这个问题的问题,因为我无法获得Blazor EditForm来绑定到一个简单的List。

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

个人.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>

因此,根据参考的微软文档,我对其进行了重构

EditForm2.razor编译并运行。。。直到人。名称实际上有一个值。然后抛出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.剃须刀是我最后一次尝试。这会编译和渲染,但一旦我尝试对编辑框进行任何操作,应用程序就会崩溃,并出现Unhandled exception rendering component: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')。我百分之九十九确信这种方法是错误的,但我现在正抓着救命稻草。

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

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

最新更新