I'm trying to iterate through some Data in a Dictionary and showing them in a table in Blazor WASM. I put an Edit button on each datarow to make the selected row editable if I will, but when I click the button, it makes every row editable in the whole table, because of the loop. What should I change in my code, to make only the selected row editable? Thank's for the possible answers ;)
@if (Metadata != null)
{
@foreach (var c in Metadata)
{
<tr>
<td><button type="submit" @onclick="toggleEdit">Edit</button></td>
@if (IsEditable)
{
<td><input type="text" class="form-control" placeholder="Key"></td>
<td><input type="text" class="form-control" placeholder="Value"></td>
}
else
{
<td>@c.Key</td>
<td>@c.Value</td>
}
</tr>
}
}
@code
{
public Dictionary<string, string> Metadata { get; set; }
public bool IsEditable = false;
private void toggleEdit()
{
IsEditable = true;
}
}
In your code, any button will apply on all rows, You need to make project know which row you wanna change.
Please follow this demo:
@{
int i = 0;
}
@if (MyProperty != null)
{
@foreach (var c in MyProperty)
{
var index = i;
<tr id="@i">
<td id="@i"><button type="submit" @onclick="()=>toggleEdit(index)">Edit</button></td>
@if (IsEditable[i])
{
<td><input type="text" class="form-control" placeholder="Key"></td>
<td><input type="text" class="form-control" placeholder="Value"></td>
}
else
{
<td>@c.Key</td>
<td>@c.Value</td>
}
</tr>
i++;
}
}
@code{
//For testing, I just hard code here
Dictionary<string, string> MyProperty = new Dictionary<string, string>()
{
{"A","AAAAA" },
{"B","BBBBB" },
{"C","CCCCC" },
{"D","DDDDD" },
};
public bool[] IsEditable;
protected override async Task OnInitializedAsync()
{
var count = MyProperty.Keys.Count;
IsEditable = new bool[count];
}
private void toggleEdit (int index)
{
IsEditable[index] = true;
}
}