[SOLVED] Blazor: How to number the rows in MudBlazor table automatically?

Issue

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.

Solution

Well, a bit crude but simplest solution would be to map current number-less object to a model that contains needed number.
Create following:

public class Model<T>
{
    public int Number {get; set;}
    public T Value {get; set;}
}

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.

<MudTd DataLabel="Nr">@context.Number</MudTd>
<MudTd DataLabel="Sign">@context.Sign</MudTd>

will become

<MudTd DataLabel="Nr">@context.Number</MudTd>
<MudTd DataLabel="Sign">@context.Value.Sign</MudTd>
// etc...

Again, it’s a bit crude on the eyes, but will do the trick.

Answered By – quain

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *