Reputation: 820
I have a Blazor EditForm like this:
<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>
Now as the user types into the InputNumber field, I want to sum up the value on all these fields. So, in the OnInput function, I do this:
public void OnInput(){
total_premium = EntryModel.VehiclePremiums.Select(vp => vp.premium).Sum();
}
This gives me a form like this:
The problem is that when I enter premium for the first car, the total is not updated. When I enter for the second car, the total is updated but current value is not included. Kind of strange behavior. The sum is always one field behind.
How should I sum up these fields as the user types in (either while inputting or after losing focus, doesn't matter)?
Upvotes: 0
Views: 1877
Reputation: 45586
Tested code here...
Note that I'm not using the InputNumber component. It's easier and more flexible to work with Html input number tag
@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; }
}
}
Upvotes: 1