Loading layout data

Display data other than the resource's records in a layout, and link it to records

Introduction

A layout may need to display data that isn't the resource's records, such as the revenue per destination calculated from the bookings, or data from another service. StellarAdmin allows you to create handlers that load the layout's items.

Writing a handler

There are two kinds of handler. For an EF Core resource, prefer an IEfCoreLayoutHandler<TEntity, TItem>, so that StellarAdmin applies the search and the scope for you. Otherwise, implement IResourceLayoutHandler<TItem>. In both, TItem is the type of the layout's items.

Reshaping EF Core records

An IEfCoreLayoutHandler<TEntity, TItem> reshapes the resource's records into the layout's items. Its ListAsync() method receives a query of the records that the search and the selected scope select, and must return the items and their total number in a ResourceListResult<TItem>. The query isn't tracked.

The example below calculates the number of bookings and the revenue per destination:

using StellarAdmin.EntityFrameworkCore;
using StellarAdmin.Resources;

public record DestinationRevenue(int DestinationId, string Destination, int Bookings, decimal Revenue);

public class DestinationRevenueHandler : IEfCoreLayoutHandler<Booking, DestinationRevenue>
{
    public async Task<ResourceListResult<DestinationRevenue>> ListAsync(
        IQueryable<Booking> bookings,
        ResourceListRequest request,
        CancellationToken cancellationToken)
    {
        var items = await bookings
            .GroupBy(booking => new
            {
                booking.Departure.Trip.DestinationId,
                booking.Departure.Trip.Destination.Name,
            })
            .OrderBy(destination => destination.Key.Name)
            .Select(destination => new DestinationRevenue(
                destination.Key.DestinationId,
                destination.Key.Name,
                destination.Count(),
                destination.Sum(booking => booking.TotalAmount)))
            .ToListAsync(cancellationToken);

        return new ResourceListResult<DestinationRevenue>(items, items.Count);
    }
}

Because the query contains only the bookings that match the search and the selected scope, searching for a booking reference displays the revenue of the matching bookings only.

Loading items yourself

An IResourceLayoutHandler<TItem> loads the items itself, for example from a custom data source or another service. Its ListAsync() method receives the search and the selected scope via the Search and Scope properties of the request parameter, and must apply them itself.

The example below loads the departures per day from a service:

using StellarAdmin.Resources;

public record DepartureDay(DateOnly Date, int Departures);

public class DepartureDaysHandler(DepartureCalendar calendar) : IResourceLayoutHandler<DepartureDay>
{
    public async Task<ResourceListResult<DepartureDay>> ListAsync(
        ResourceListRequest request,
        CancellationToken cancellationToken)
    {
        var items = await calendar.ListDaysAsync(request.Search, cancellationToken);

        return new ResourceListResult<DepartureDay>(items, items.Count);
    }
}

StellarAdmin registers the handler as a scoped service, unless you've already registered it, so you can inject services into its constructor.

Displaying the items in a table

To display the items in a table, pass the item type and the handler as the type arguments of AddTable<TItem, THandler>(). The columns select the properties of the item type:

resource.Index(
    index => index.EnableSearch(term => booking => booking.Reference.Contains(term)),
    layouts =>
    {
        layouts.AddTable("bookings", table =>
        {
            table.Columns(columns => columns.Add(booking => booking.Reference));
        });
        layouts.AddTable<DestinationRevenue, DestinationRevenueHandler>("revenue", table =>
        {
            table.Title = "Revenue per destination";
            table.Icon = "chart-column";
            table.Columns(columns =>
            {
                columns.Add(item => item.Destination);
                columns.Add(item => item.Bookings);
                columns.Add(item => item.Revenue);
            });
        });
    });
The bookings index page with the Revenue per destination table selected, listing destinations with their bookings and revenue

A table of items has no row details and no inline editing. Its rows have no row actions unless you link them to records.

Sorting and paging the items

When the table has sortable columns or paging, the handler must sort and page the items. StellarAdmin passes the requested sort and page via the Sort and Paging properties of the request parameter. Sort.Field is the name of the property the column sorts by.

The example below makes the revenue column sortable and pages the table:

layouts.AddTable<DestinationRevenue, DestinationRevenueHandler>("revenue", table =>
{
    table.Columns(columns =>
    {
        columns.Add(item => item.Destination);
        columns.Add(item => item.Revenue, column => column.Sortable());
    });
    table.DefaultSortByDescending(item => item.Revenue);
    table.EnablePaging();
});

The handler below sorts by revenue when it's requested, breaks ties by destination, and returns only the items for the requested page:

public async Task<ResourceListResult<DestinationRevenue>> ListAsync(
    IQueryable<Booking> bookings,
    ResourceListRequest request,
    CancellationToken cancellationToken)
{
    var rows = bookings
        .GroupBy(booking => new
        {
            booking.Departure.Trip.DestinationId,
            booking.Departure.Trip.Destination.Name,
        })
        .Select(destination => new
        {
            destination.Key.DestinationId,
            destination.Key.Name,
            Bookings = destination.Count(),
            Revenue = destination.Sum(booking => booking.TotalAmount),
        });

    rows = request.Sort is { Field: nameof(DestinationRevenue.Revenue) } sort
        ? sort.Direction == ResourceSortDirection.Ascending
            ? rows.OrderBy(row => row.Revenue).ThenBy(row => row.Name)
            : rows.OrderByDescending(row => row.Revenue).ThenBy(row => row.Name)
        : rows.OrderBy(row => row.Name);

    var total = await rows.CountAsync(cancellationToken);
    if (request.Paging is { } paging)
        rows = rows.Skip((paging.Page - 1) * paging.PageSize).Take(paging.PageSize);

    var items = await rows
        .Select(row => new DestinationRevenue(row.DestinationId, row.Name, row.Bookings, row.Revenue))
        .ToListAsync(cancellationToken);

    return new ResourceListResult<DestinationRevenue>(items, total);
}

The handler sorts and pages an anonymous type, and creates the DestinationRevenue items last, because EF Core can't translate a sort on the properties of a record that the query creates.

Return the total number of items with the page, as total does above, so that the table can display how many pages there are.

Displaying the items in a partial view

To display the items in a partial view, pass the item type and the handler as the type arguments of AddPartial<TItem, THandler>():

layouts.AddPartial<DestinationRevenue, DestinationRevenueHandler>("revenue-cards", "_RevenueCards");

The partial view's model is a ResourceLayoutModel<DestinationRevenue>, with the handler's items in Items. A partial view has no paging, so Sort and Paging of the request are always null, and the handler must return every item. The model has the same members as the model of a partial view of records.

Areas/StellarAdmin/Views/bookings/_RevenueCards.cshtml
@using StellarAdmin.Resources
@model ResourceLayoutModel<DestinationRevenue>

<div class="grid grid-cols-3 gap-4">
    @foreach (var item in Model.Items)
    {
        <sa-card>
            <sa-card-header>
                <sa-card-title>@item.Destination</sa-card-title>
                <sa-card-description>@item.Bookings bookings</sa-card-description>
            </sa-card-header>
            <sa-card-content>@item.Revenue.ToString("C")</sa-card-content>
        </sa-card>
    }
</div>

Linking items to records

By default, items don't link to any record, so a table of items has no row actions, and GetViewUrl() and GetEditUrl() of the partial view's model return null. To link each item to a record, call HasRecordKey() or LinkTo<TOther>() in the layout's callback.

Linking items to the resource's records

When each item belongs to one of the resource's records, call HasRecordKey() with a function that returns the record's key. The rows of a table then display the view, edit and delete actions that are enabled on the resource, and RowActions() can hide them. In a partial view, GetViewUrl() and GetEditUrl() return the URLs of the record's pages.

The example below lists each booking's balance, with the actions of the booking:

public record BookingBalance(int BookingId, string Reference, decimal Total, decimal Paid);

layouts.AddTable<BookingBalance, BookingBalanceHandler>("balances", table =>
{
    table.HasRecordKey(item => item.BookingId);
    table.Columns(columns =>
    {
        columns.Add(item => item.Reference);
        columns.Add(item => item.Total);
        columns.Add(item => item.Paid);
    });
});

Linking items to another resource

When each item belongs to a record of another resource, call LinkTo<TOther>() with the other resource's type, and a function that returns the record's key. The rows of a table then display a view action that opens the other record's view page. In a partial view, GetViewUrl() returns the URL of that page, and GetEditUrl() returns null.

The example below links each row of the revenue table to the destination:

layouts.AddTable<DestinationRevenue, DestinationRevenueHandler>("revenue", table =>
{
    table.LinkTo<Destination>(item => item.DestinationId);
    table.Columns(columns =>
    {
        columns.Add(item => item.Destination);
        columns.Add(item => item.Revenue);
    });
});

The other resource must have a view page. If it doesn't, the items don't link, and StellarAdmin reports a configuration problem. When the signed-in user isn't authorized to view the other resource, the items don't link either.

When the function passed to HasRecordKey() or LinkTo<TOther>() returns null, the item doesn't link, such as for a row with the total of all bookings. A layout can link its items in only one way, so calling both methods throws an InvalidOperationException.

On this page