In a table, each row has a button
and a checkbox
. On click of the button I want to toggle the enable/disable state of the checkbox
(Not the checked value). My approach is actually toggling the enable/disable state for all the checkbox
in the table, however I want the affect for only the particular row.
<tbody>
@foreach (var eachData in dataList)
{
<tr>
<td>
<button @onclick="HandleToggleEvent">@SelectionButtonLabel</button>
</td>
<td>eachData.val1</td>
<td>
<input type="checkbox" id="flexSwitchCheckDefault" @bind="eachData.IsChecked" disabled=@(!IsRowSelected)>
</td>
</tr>
}
</tbody>
@code {
private bool IsRowSelected { get; set; }
private string SelectionButtonLabel = "Edit";
private void HandleToggleEvent()
{
if (!IsRowSelected)
{
IsRowSelected = true;
SelectionButtonLabel = "Cancel";
}
else
{
IsRowSelected = false;
SelectionButtonLabel = "Edit";
}
}
}
CodePudding user response:
You need an indexer instead.
private List dataList = new List() { "One", "Two", "Three" };
private List<bool> IsRowSelected { get; set; } = new List<bool>();
private string SelectionButtonLabel = "Edit";
protected override void OnInitialized()
{
foreach (var item in dataList) IsRowSelected.Add(false);
}
private void HandleToggleEvent(int idx)
{
if (!IsRowSelected[idx])
{
IsRowSelected[idx] = true;
SelectionButtonLabel = "Cancel";
}
else
{
IsRowSelected[idx] = false;
SelectionButtonLabel = "Edit";
}
}
Don't forget to initialize the list and populate it with values for each value in dataList
. Then, in your razor code:
<tbody>
@for (int i = 0; i < dataList.Count; i )
{
int idx = i; //This is important to avoid closing on i;
<tr>
<td>
<button @onclick="() => HandleToggleEvent(idx)">@SelectionButtonLabel</button>
</td>
<td>dataList[i].val1</td>
<td>
<input type="checkbox" id="flexSwitchCheckDefault" disabled="@(!IsRowSelected[idx])">
</td>
</tr>
}
</tbody>
Then you need to do the same with SelectionButtonLabel.