Blazor 编辑窗体从列表绑定



我正在尝试制作一个页面来编辑客户数据。

客户对象有一个电话号码(字符串(列表,因为大多数都有固定电话和手机。 我似乎找不到将其放入编辑表单的方法。我尝试使用 foreach 循环,但它无法绑定到此循环。 我还尝试在循环中使用本地副本并绑定到该副本。这有效,但是按下提交按钮后我无法检索更改。 我做错了什么?正确的方法是什么?我似乎找不到任何涵盖此内容的教程。

我已经将我的页面重新创建为做同样事情的最小页面:

这是我的客户类

public class Customer
{
public string Name { get; set; }
// arbitrary extra fields
public List<string> phoneNumber { get; set; }
}
}
public class CustomerService
{
Customer jeff;
public CustomerService()
{
jeff = new Customer
{
Name = "Jeff",
phoneNumber = new List<string> { "123456", "654321" },
};
}
public Customer getCustomer()
{

return jeff;
}
public void setCustomer(Customer cust)
{
jeff = cust;
}
}

和我的页面

<EditForm Model="@customer" OnSubmit="@submitChanges">
<InputText id="name" @bind-Value="@customer.Name" /><br/>
<!-- How do i link the multiple phonenumbers-->
@foreach(string phone in customer.phoneNumber)
{
//this does not compile
//<InputText @bind-Value="@phone"/>
//this compiles but i can't find how to acces the data afterward ???
string temp = phone;
<InputText @bind-Value="@temp"/>
}
@for(int i=0;i<customer.phoneNumber.Count();i++)
{
//this compiles but chrashed at page load
// <InputText @bind-Value="@customer.phoneNumer[i]"/>
}

<button type="submit">submit</button>

</EditForm>
代码部分
@code {        
Customer customer;

protected override void OnInitialized()
{
customer = _data.getCustomer();           
}
private void submitChanges()
{
_data.setCustomer(customer);
}
}

>@Wolf,今天我读到了ObjectGraphDataAnnotationsValidator,它被用来代替DataAnnotationsValidator组件

验证绑定模型的整个对象图,包括 集合型和复杂型属性

强调包括收集。因此,我搜索了一个在 EditForm 中实现集合的示例,但找不到。经过一些努力,我成功地做到了。代码如下:

@page "/"
@using Microsoft.AspNetCore.Components.Forms
@using System.ComponentModel.DataAnnotations;
<EditForm Model="@customer" OnSubmit="@submitChanges">
<DataAnnotationsValidator />
<p>
<InputText id="name" @bind-Value="customer.Name" /><br />
</p>
@foreach (var phone in customer.phones)
{
<p>
<InputText @bind-Value="phone.PhoneNumber" /> 
</p>
}
<p>
<button type="submit">submit</button>
</p>
</EditForm>
<div>
<p>Edit  customer</p>
<p>@customer.Name</p>
@foreach (var phone in customer.phones)
{
<p>@phone.PhoneNumber</p>
}
</div>
@code {
Customer customer;

protected override void OnInitialized()
{
customer = new Customer();
}
private void submitChanges()
{
// _data.setCustomer(customer);
}
public class Customer
{
public string Name { get; set; } = "jeff";
//[ValidateComplexType]
public List<Phone> phones { get; } = new List<Phone>() { new Phone 
{PhoneNumber = "123456" }, new Phone {PhoneNumber = "654321" }};
}
public class Phone
{
public string PhoneNumber { get; set; }
}
}

希望这有帮助...

use     
word-break: break-all;
word-wrap: break-word;
white-space: initial;

最新更新