Blazor EditForm从列表绑定 [英] Blazor EditForm bind from List
本文介绍了Blazor EditForm从列表绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个页面来编辑客户数据。
Customer对象有一个电话枚举号码列表(字符串),因为大多数都有座机和手机。 我似乎找不到一种方法把它写成编辑的形式。我尝试使用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; }
}
}
希望这会有帮助.
这篇关于Blazor EditForm从列表绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文