【发布时间】: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<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>
【问题讨论】:
标签: c# blazor blazor-server-side