Blazor EditForm 添加 InputNumber 字段
Posted
技术标签:
【中文标题】Blazor EditForm 添加 InputNumber 字段【英文标题】:Blazor EditForm adding InputNumber fields 【发布时间】:2021-01-25 21:32:00 【问题描述】:我有一个这样的 Blazor EditForm:
<EditForm Model="EntryModel" OnValidSubmit="HandleValidSubmit" @oninput="OnInput" >
//...other stuff...
@foreach (var v in EntryModel.VehiclePremiums)
<tr>
<td>@v.vehicleid</td>
<td>@v.vehicleMake</td>
<td>@v.vehicleModel</td>
<td><InputNumber @bind-Value="@v.premium" /></td>
</tr>
//...other stuff
</EditForm>
现在当用户输入 InputNumber 字段时,我想总结所有这些字段的值。 所以,在 OnInput 函数中,我这样做:
public void OnInput()
total_premium = EntryModel.VehiclePremiums.Select(vp => vp.premium).Sum();
这给了我这样的表格:
问题是,当我输入第一辆车的保费时,总数没有更新。当我进入第二辆车时,总数会更新,但不包括当前值。一种奇怪的行为。总和总是落后一个字段。
当用户输入时,我应该如何总结这些字段(无论是在输入时还是在失去焦点后,都没有关系)?
【问题讨论】:
【参考方案1】:测试代码在这里...
请注意,我没有使用 InputNumber 组件。使用 html 输入数字标签更容易、更灵活
@page "/"
<EditForm Model="entryModel" OnValidSubmit="HandleValidSubmit">
<InputText @bind-Value="entryModel.ID"></InputText>
<table>
<thead>
<tr>
<td>Make</td>
<td>Model</td>
<td>Premium</td>
<td>@total_premium.ToString()</td>
</tr>
</thead>
<tbody>
@foreach (var v in entryModel.VehiclePremiums)
<tr>
<td>@v.VehicleID</td>
<td>@v.VehicleMake</td>
<td>@v.VehicleModel</td>
<td>
<input type="number" value="@v.Premium" @onchange="@((args) => v.Premium = Convert.ToInt32(args.Value);
total_premium = entryModel.VehiclePremiums.Select(vp => vp.Premium).Sum();)" />
</td>
</tr>
</tbody>
</table>
</EditForm>
@code
private EntryModel entryModel;
private int total_premium;
private void HandleValidSubmit()
protected override void OnInitialized()
entryModel = new EntryModel
ID = "1",
VehiclePremiums = new List<VehiclePremium>
new VehiclePremiumVehicleID = "1", VehicleMake="Make1", VehicleModel="Model1", Premium=0,
new VehiclePremiumVehicleID = "2", VehicleMake="Make2", VehicleModel="Model2", Premium=0,
new VehiclePremiumVehicleID = "3", VehicleMake="Make3", VehicleModel="Model3", Premium=0,
new VehiclePremiumVehicleID = "4", VehicleMake="Make4", VehicleModel="Model4", Premium=0
;
public class VehiclePremium
public string VehicleID get; set;
public string VehicleMake get; set;
public string VehicleModel get; set;
public int Premium get; set;
public class EntryModel
public string ID get; set;
public List<VehiclePremium> VehiclePremiums get; set;
【讨论】:
以上是关于Blazor EditForm 添加 InputNumber 字段的主要内容,如果未能解决你的问题,请参考以下文章
使用 Blazored.fluentValidator 在 Blazor 中使用一个 Editform 验证模型列表