I have a form on a blazor website that I am trying to define. The user selects how many textboxes to create. Based on that number, they are created. I need to then total the number typed into these textboxes.
I can create the desired number of text boxes, but where I'm struggling is dynamically binding a value to it so that I can create a function to total the numbers typed in. I've done some research, and see I can bind them to a collection.
This is what I'm trying... But it is not working, any help would be great.
<td>EE Only</td>
@{
for (int i = 0; i < AppData.PlanOption; i++)
{
<td>
<input @bind="eevalue.Vals" @bind:event="oninput" @onchange="() => IncrementEETotal()" />
</td>
}
}
<td style="background-color: rgb(192, 206, 219);"><input class="field" readonly @bind="eeTotal" /></td>
@code {
private void IncrementEETotal()
{
eeTotal = eevalue.Vals.Sum();
}
public class EEVals
{
public List<int> Vals { get; set; } = new List<int>();
}
public class EEItem
{
public int val { get; set; }
public string name { get; set; }
}
public EEVals eevalue { get; set; } = new EEVals();
}
This small code snipped will helps you to understand how to dynamically create inputs:
Num items: <input type="number" value="@N" @oninput="onchange_n"> Sum: @total <br>
@foreach (var i in Enumerable.Range(0,N))
{
var ii = i;
<input type="number" value="@MyList[ii]"
@oninput="(e) => resum(ii, e)"><br>
}
@code
{
private int N = 0, total = 0;
private List<int> MyList = new List<int>();
private void onchange_n(ChangeEventArgs e)
{
N = 0;
if (Int32.TryParse(e.Value.ToString(), out int n)) N = n;
MyList.Clear();
MyList.AddRange(Enumerable.Range(0,N).Select(_=>0));
StateHasChanged();
}
private void resum(int i, ChangeEventArgs e)
{
var n = 0;
if (Int32.TryParse(e.Value.ToString(), out int auxn)) n = auxn;
MyList[i] = n;
total = MyList.Sum(x=>x);
}
}

Check it out at https://blazorrepl.com/repl/cPOQEsvK41rqDkvC44
The code is self-explanatory, but, if you need some clarifications don't hesitate to let a comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With