I have the following table rendering in my blazor project:
<table class="table table-bordered accountTable @HighlightSelected" >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@if (Accounts != null)
{
@foreach (var account in Accounts)
{
<tr @onclick="@(() => ReturnRowData(account))">
<td >@account.Id</td>
<td >@account.Name</td>
</tr>
}
}
else
{
<p>No accounts to display...</p>
}
</tbody>
</table>
@code{
[Parameter]
public List<Account> Accounts { get; set; }
[Parameter]
public EventCallback<Account> OnRowClicked{get;set;}
public string HighlightSelected = "normal";
public async void ReturnRowData(Account account)
{
HighlightSelected = "highlight";
await OnRowClicked.InvokeAsync(account);
}
}
When a row on this table is clicked, it is returning the selected rows data back to my index page for use in other functions. What I'm trying to do here is add a new background colour to the selected row.
The parameter on the table @HighlightSelected is a string variable which I am using to substitute in my desired CSS change. However, the css change is added to every single row instead of just the single selected.
In my css I have tried different combinations of targeting the specific td I want, but it always results in the whole table being highlighted. Example as
.highlight table tbody tr.highlight td {
background-color: red;
}
What is it that I'm doing wrong?
I'm aware that this can be done with javascript but I would like to avoid that at all costs if at all possible.
Whenever I'm using a List, I often create an individual instance for selection and comparison.
@page "/accounts"
<table class="table table-bordered accountTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@if (AccountsList != null)
{
@foreach (var account in AccountsList)
{
string colorClass= (account == SelectedAccount) ? "MyHighlightClass" : "";
<tr class="@colorClass" style="color:navy; cursor:pointer; text-decoration:underline" @onclick="() => { ReturnRowData(account); SelectedAccount = account; }">
<td>@account.Id</td>
<td>@account.Name</td>
</tr>
}
}
else
{
<p>No accounts to display...</p>
}
</tbody>
</table>
@if (SelectedAccount.Id != 0)
{
<h3>Selected account #@SelectedAccount.Id (@SelectedAccount.Name) </h3>
}
@code {
public class Account
{
public int Id;
public string Name = "";
}
[Parameter]
public List<Account> AccountsList { get; set; } = new List<Account>() {
new Account(){ Id = 1, Name="John" },
new Account(){ Id = 2, Name="Jeff" },
new Account(){ Id = 3, Name="Jane" }
};
Account SelectedAccount { get; set; } = new Account();
void ReturnRowData(Account account)
{
// Do data stuff.
}
}
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