I want to create a simple expandable table in Blazor WebAssembly. I added some HTML code like the following:
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>User</th>
<th>Date</th>
<th>Status</th>
<th>Reason</th>
</tr>
</thead>
<tbody>
<tr data-widget="expandable-table" aria-expanded="false">
<td>183</td>
<td>John Doe</td>
<td>11-7-2014</td>
<td>Approved</td>
<td>Lorem Ipsum is simply dummy text</td>
</tr>
<tr class="expandable-body">
<td colspan="5">
<p>
Lorem Ipsum is simply dummy text
</p>
</td>
</tr>
</tbody>
</table>
The row with details is always collpased also if I click on it. Is there a simple way to implement it without using external component? If no, what component do you recommend?
An example of what I mean with "Expandable table" is here.
I came up with a solution based on the default "WeatherForecast" that comes from the Blazor Server template. The basic idea is to put a flag in the model that is used to represent table data.
WeatherForecast.cs
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
//new fields added below
public bool IsRowExpanded { get; set; } = false;
public string ExpandableContent { get; set; } = "Lorem Ipsum";
}
FetchData.razor
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr @onclick="() => forecast.IsRowExpanded = !forecast.IsRowExpanded">
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
if (forecast.IsRowExpanded)
{
<tr>@forecast.ExpandableContent</tr>
}
}
</tbody>
</table>
When you click on a row (for example the 2nd row) it will look like this:
With Bootstrap, the built in jQuery/JavaScript code is not going to work out-of-the-box like traditional MVC pages do.
If you want to expand/collapse rows, you've got two options with Blazor.
Invoke the Bootstrap jQuery/JavaScript by injecting IJSRuntime onto the page and calling InvokeAsync()
.
Write your own expand/collapse component and wrap each row in it - something like
// CollapsibleTableRow.
<tr @onclick=Toggle>
@if(_show)
{
@ChildContent
}
</tr>
@code
{
[Parameter] public RenderFragment ChildContent { get; set; }
private bool _show { get; set; } = false;
private void Toggle()
{
_show = !_show;
}
}
Use
<table>
<tbody>
@foreach(var item in items)
{
<CollapsibleTableRow>
<td>@item.Thing</td>
<td>@item.Thing2</td>
</CollapsibleTableRow>
}
</tbody>
</table>
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