In my app, I have the _totalOutput field which is calculated from the list: decimal _totalOutcome => _evaluationList.Sum(e => e.Outcome);
The list contains a class of several properties which I iterate on the page and render as text and one checkbox. When I click on the checkbox then the value of Score, Weight, and Outcome (last column) changes appropriately. But "Total Outcome" renders one step behind. Calculation steps:
- if checked (unchecked) Score = 100 (0 is unchecked)
- Outcome = Score * (Weight / totalWeight)
- Total outcome summarized
I added force refresh button on the page for test purposes (StateHasChanged). After checking boxes if I click on the button then totalOutcome renders correctly.
How can I show an actual totalOutcome on the page?
Index.razor
@page "/"
<div style="margin-bottom:16px">Total Outcome: @_totalOutcome</div>
<button style="margin-bottom:16px" onclick="@(() => StateHasChanged())">Force refresh (StateHasChanged)</button>
@foreach (var item in _evaluationList)
{
<div style="display:flex">
<div style="margin-right: 32px">
@item.Id
</div>
<div style="margin-right: 32px">
@item.Name
</div>
<div style="margin-right: 32px">
<input type="checkbox" @bind-value="@item.Enabled">
</div>
<div style="margin-right: 32px; width: 40px">
@{
item.Score = item.Enabled ? 100 : 0;
<div>@item.Score</div>
}
</div>
<div style="margin-right: 32px; width: 40px">
@item.Weight
</div>
<div style="margin-right: 32px; width: 40px">
@{
var totalWeight = _evaluationList.Sum(e => e.Weight);
item.Outcome = Math.Round(item.Score * (item.Weight / totalWeight), 2);
<div>@item.Outcome</div>
}
</div>
</div>
}
@code {
List<Evaluation> _evaluationList = new List<Evaluation>()
{
new Evaluation { Id=1, Name="Item 1", Enabled=false, Score=0, Weight=10 },
new Evaluation { Id=2, Name="Item 2", Enabled=false, Score=0, Weight=20 },
new Evaluation { Id=3, Name="Item 3", Enabled=false, Score=0, Weight=30 },
new Evaluation { Id=4, Name="Item 4", Enabled=false, Score=0, Weight=40 },
new Evaluation { Id=5, Name="Item 5", Enabled=false, Score=0, Weight=50 },
new Evaluation { Id=6, Name="Item 6", Enabled=false, Score=0, Weight=60 },
new Evaluation { Id=7, Name="Item 7", Enabled=false, Score=0, Weight=70 },
new Evaluation { Id=8, Name="Item 8", Enabled=false, Score=0, Weight=80 },
};
decimal _totalOutcome => _evaluationList.Sum(e => e.Outcome);
public class Evaluation
{
public int Id { get; set; }
public string? Name { get; set; }
public bool Enabled { get; set; }
public decimal Score { get; set; }
public decimal Weight { get; set; }
public decimal Outcome { get; set; }
}
}
