How does data binding for Lists works in C# / Blazor?
Posted 2 years ago
by goaga
Edited 2 years ago
I do not understand how to bind (2-way) the four Lists to the input elements. I tried different solutions with foreach and while but nothing worked for me.
The problem with my solution is, if i change for example finput field with binding D_List[0] then the D_List[1] also changes to the same value.
...
foreach (var item in D_List)
{
<tr>
<td>
<input id=D_List @bind="D_List[D_List.IndexOf(item)]">
</td>
<td>
<input id=F_List @bind="F_List[F_List.IndexOf(item)]">
</td>
<td>
<input id=HB_List @bind="HB_List[HB_List.IndexOf(item)]">
</td>
<td>
@Diagonalen_List[Diagonalen_List.IndexOf(item)]
</td>
<td>
<button type="button" @onclick="(() => delBtnPressed(i))">Delete row</button>
</td>
</tr>
}
...
@code {
#nullable disable
IMpaFunc mpaFunc = new MpaFunc();
// Listen für Eingabeparameter
List<double> D_List { get; set; }
List<double> F_List { get; set; }
List<double> HB_List { get; set; }
// Liste für Ergebnisse
List<double> Diagonalen_List { get; set; }
// Counter für Anzahl Zeilen
int anzahlZeilen;
int minimumZeilen;
int maximumZeilen;
// Intialisiere Listen & Attrbiute und füge default Werte für die erste Zeile hinzu
protected override void OnInitialized() {
anzahlZeilen = 1;
minimumZeilen = 1;
maximumZeilen = 5;
D_List = new List<double>();
F_List = new List<double>();
HB_List = new List<double>();
Diagonalen_List = new List<double>();
D_List.Add(10);
F_List.Add(0.1);
HB_List.Add(100);
Diagonalen_List.Add(mpaFunc.BrinellEindruckdurchmesser(10, 0.1, 100));
}
// Automatische Berechnung der Brinellhärte bei Start und Änderung der Parameter
string AutoBerechnung()
{
berechneDiagonalen();
return null;
}
// Aufruf der Brinellberechnungsfunktion
void berechneDiagonalen()
{
for(int i = 0; i < anzahlZeilen; i++)
{
double D = D_List[i];
double F = F_List[i];
double HB = HB_List[i];
Diagonalen_List[i] = mpaFunc.BrinellEindruckdurchmesser(D, F, HB);
}
}
void addBtnPressed()
{
zeileHinzufuegen();
}
void delBtnPressed(int rowIndex)
{
if(anzahlZeilen > minimumZeilen)
{
D_List.RemoveAt(rowIndex);
F_List.RemoveAt(rowIndex);
HB_List.RemoveAt(rowIndex);
Diagonalen_List.RemoveAt(rowIndex);
anzahlZeilen--;
}
}
void zeileHinzufuegen()
{
if (anzahlZeilen < maximumZeilen)
{
D_List.Add(10);
F_List.Add(0.1);
HB_List.Add(100);
Diagonalen_List.Add(mpaFunc.BrinellEindruckdurchmesser(10, 0.1, 100));
anzahlZeilen++;
}
}
}
-----------------
Another solution was this one but it also didnt work:
-...
<tbody>
@{
int i = 0;
@while(i<anzahlZeilen)
{
<tr>
<td>
<input id=D_List @bind="D_List[i]">
</td>
<td>
<input id=F_List @bind="F_List[i]">
</td>
<td>
<input id=HB_List @bind="HB_List[i]">
</td>
<td>
@Diagonalen_List[i]
</td>
<td>
<button type="button" @onclick="(() => delBtnPressed(i))">Delete row</button>
</td>
</tr>
i++;
}
}
</tbody>
....
Someone is typing...
Post a Reply
You must be logged in to add a new post.
Number of online users: 0