我是Blazor页面的新手。我正在尝试制作一个页面来编辑客户数据。 客户对象具有phonenumbers(string)的列表,因为大多数对象都有固定电话和手机。 我似乎找不到一种将其放入editform中的方法。我尝试使用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);
}
}
答案 0 :(得分:2)
@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; }
}
}
希望这对您有帮助...