I have an ASP.NET Blazor server project using MudBlazor library to create an HTML table. My issue is with the numbering. In the example code below, the numbering of the rows is retrieved from the class property. However, in my class I don’t have a number
property and it’s not nice to have a number property in all classes that I intend to display in tables.
Since the table accepts a list of items, is there a way of getting the index of the item being rendered and use it instead of @context.Number
to display the row number in the MudBlazor table?
<MudTable Items="@Elements.Take(4)" Hover="true" Breakpoint="Breakpoint.Sm" Loading="@_loading" LoadingProgressColor="Color.Info">
<HeaderContent>
<MudTh>Nr</MudTh>
<MudTh>Sign</MudTh>
<MudTh>Name</MudTh>
<MudTh>Position</MudTh>
<MudTh>Molar mass</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Nr">@context.Number</MudTd>
<MudTd DataLabel="Sign">@context.Sign</MudTd>
<MudTd DataLabel="Name">@context.Name</MudTd>
<MudTd DataLabel="Position" HideSmall="_hidePosition">@context.Position</MudTd>
<MudTd DataLabel="Molar mass">@context.Molar</MudTd>
</RowTemplate>
</MudTable>
<MudSwitch @bind-Checked="_hidePosition">Hide <b>position</b> when Breakpoint=Xs</MudSwitch>
<MudSwitch @bind-Checked="_loading">Show Loading</MudSwitch>
This example code can be found in MudBlazor Table.
4
Answers
It is better to use index of list as it is much simpler to implement to show the row numbers in a table.
@(Elements.IndexOf(context)+1)
Well, a bit crude but simplest solution would be to map current number-less object to a model that contains needed number.
Create following:
Then order your original collection by some property of your choosing and iterate through, each time creating new
Model
object with consecutive Number and Value of the original object.Use this new model as display data source for the table and all should go just fine.
will become
Again, it’s a bit crude on the eyes, but will do the trick.
With Linq’s TakeWhile you can count elements until you find element that match element of row you’re currently in:
Let’s use a counter variable and increment it for each row template
An example that I’m using: