我有一个这样的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();
}
问题是,当我为第一辆车输入溢价时,总数没有更新。当我进入第二辆车时,总数会更新,但不包括当前值。有点奇怪的行为。总和总是落后一个字段。
当用户输入时(在输入时或失去焦点后,没关系),我应该如何总结这些字段?
答案 0 :(得分: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 VehiclePremium{VehicleID = "1", VehicleMake="Make1", VehicleModel="Model1", Premium=0},
new VehiclePremium{VehicleID = "2", VehicleMake="Make2", VehicleModel="Model2", Premium=0},
new VehiclePremium{VehicleID = "3", VehicleMake="Make3", VehicleModel="Model3", Premium=0},
new VehiclePremium{VehicleID = "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; }
}
}