我正在尝试制作一个页面来编辑客户数据。
客户对象有一个电话号码(字符串)列表,因为大多数人都有固定电话和手机。
我似乎找不到一种方法将其放入编辑表单中。我尝试使用 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,今天我读到了对象图数据注释验证器 https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1#nested-models-collection-types-and-complex-types它用来代替数据注释验证器成分
验证绑定模型的整个对象图,包括
集合类型和复杂类型属性
强调包括收藏。因此,我搜索了在 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; }
}
}
希望这可以帮助...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)