MentorAgent Docs
Menu

Questa pagina non è ancora tradotta in italiano: qui la trovi in inglese.

Guida praticaPacchetti: Novior.MentorAgent.Abstractions, Novior.MentorAgent, Novior.MentorAgent.Blazor

Forms and grids

Register a Blazor form as one UI action that the model fills, and a grid as UI actions that open a row, sort and filter, with sensitive fields left out.

In questa pagina

Use this page to let the agent fill in a form of a Blazor page, and open, sort and filter the rows of a grid. A page registers its form, or its grid, with one line of code. MentorAgent then gives the model UI actions of the page: fill_<form> for a form, and open_<grid>_row, sort_<grid> and filter_<grid> for a grid. Your page does not write one action for each field or column.

Both are for Blazor pages: Blazor Server, Blazor WebAssembly and .NET MAUI Blazor Hybrid. A React, Angular or other front end has no ready-made actions for forms and grids in 1.5.0.

  • Choose it when the page already has the form or the grid, and the user asks the agent to fill it in, or to find a row.
  • Register a UI action of your own with RegisterUIAction when the page does something else, for example highlights a row or opens a dialog.
  • Use a recipe when the procedure takes several steps, or must be approved outside your code.
  • Use an action when the work can run on the server, with no page in between: saving the form, for example.

The fields are the public properties of the form's model that have a getter and a setter of a simple type:

NewTicket.cs
public enum TicketPriority { Low, Normal, High }

// The form's model: each simple property with a setter is a field
public sealed class NewTicket
{
    public string Title { get; set; } = "";
    public int Quantity { get; set; } = 1;
    public TicketPriority Priority { get; set; } = TicketPriority.Normal;
    public bool Urgent { get; set; }
    public DateOnly? DueDate { get; set; }

    // Left out with Exclude: the model never reads it
    public string? InternalNotes { get; set; }

    // Sensitive by its name: never offered to the model
    public string? Pin { get; set; }
}

The page registers the form in OnInitialized, with a name, a description for the model and the page's IJSRuntime. Each field of the page has a data-mentor-id attribute with the value "<form>.<field>". The field is named as the model writes it: dueDate for DueDate.

NewTicketPage.razor
@page "/support/tickets/new"
@inject IMentorPageContext PageContext
@inject IJSRuntime JS
@implements IDisposable

@* SaveAsync is your own method: the action of the form never calls it *@
<EditForm Model="_ticket" OnValidSubmit="SaveAsync">
    <InputText data-mentor-id="ticket.title" @bind-Value="_ticket.Title" />
    <InputNumber data-mentor-id="ticket.quantity"
                 @bind-Value="_ticket.Quantity" />
    <InputSelect data-mentor-id="ticket.priority"
                 @bind-Value="_ticket.Priority">
        @foreach (var p in Enum.GetValues<TicketPriority>())
        {
            <option value="@p">@p</option>
        }
    </InputSelect>
    <InputCheckbox data-mentor-id="ticket.urgent"
                   @bind-Value="_ticket.Urgent" />
    <InputDate data-mentor-id="ticket.dueDate" @bind-Value="_ticket.DueDate" />
    <InputTextArea @bind-Value="_ticket.InternalNotes" />
    <InputText type="password" @bind-Value="_ticket.Pin" />
    <button type="submit">Save</button>
</EditForm>

@code {
    private readonly NewTicket _ticket = new();

    protected override void OnInitialized()
    {
        // Names the page, then registers its form as the UI action fill_ticket
        PageContext.SetPageName("New ticket")
            .RegisterForm<NewTicket>("ticket",
                "The form of a new support ticket", JS,
                o => o.Exclude(nameof(NewTicket.InternalNotes)));
        // Tells navigate_to that the page has registered its actions
        PageContext.SignalReady();
    }

    // Removes what this page registered, when the user leaves the page
    public void Dispose() => PageContext.Clear("New ticket");
}
  • The field types. A field is a text, a number, a bool (a check box), an enum (a select that lists the names of the enum), a Guid, a date or a time. The model writes a DateOnly as yyyy-MM-dd, and a TimeOnly as HH:mm, or HH:mm:ss with its seconds. A DateTime is written as the model gives it, and an InputDate may not accept it, so use DateOnly for a date. A property of another type is not a field.
  • The page's elements. Put a text, a number, a Guid or a date in an input, a textarea or an editable element. Put an enum in a select or an ARIA combobox, not in radio buttons. Put a bool in a check box, a radio button, or an ARIA check box or switch. An option is chosen by its label, so a select whose labels are not the names of the enum, translated labels for example, does not find the option.
  • What the model reads. One action, fill_ticket, with the form's description and its fields with their types: { title: string, quantity: integer, priority: string (Low|Normal|High), urgent: boolean, dueDate: string (date, yyyy-MM-dd)? }. The model gives only the fields that it fills. MentorAgent checks each value against the type of its field before anything runs in the page.
  • How it fills. The fields that the model gives are written in the order of the properties of the form's class, as a user would type them, so that @bind and the form's validation receive them.
  • It never submits. The action stops when the fields are written, and the model is told so. Sending the form stays an action of your own. When sending the form changes data, make it an action that asks for a confirmation. A UI action asks for no confirmation of its own, unless a policy adds one.

The fourth argument changes how the form is read. Name a field by its property, nameof(NewTicket.InternalNotes) or internalNotes. A name that is not a field throws an exception when the form is registered:

OptionWhat it does
Exclude(fields)Leaves the fields out: the model is not told of them and cannot fill them
IncludeSensitive(fields)Includes sensitive fields, which a form leaves out otherwise
Selector(field, selector)Finds the field with a CSS selector of your own, in place of its data-mentor-id
ClaimPage.razor
@code {
    protected override void OnInitialized() =>
        // "Token" makes the field sensitive, but the user reads this one
        // from the parcel's label, and may say it to the assistant
        PageContext.RegisterForm<ParcelClaim>("claim",
            "The claim for a lost parcel", JS, o => o
                .IncludeSensitive(nameof(ParcelClaim.TrackingToken))
                .Selector(nameof(ParcelClaim.Description), "#claim-text"));
}

A sensitive field is never offered to the model unless you include it with IncludeSensitive. A property is sensitive when it has one of these signs:

  • [DataType(DataType.Password)], [DataType(DataType.CreditCard)] or [PasswordPropertyText(true)];
  • a name that says that it holds a password, a secret, a token, a PIN, a card's number or code, an IBAN, an API key, a one-time code, credentials or a social security number. For example NewPassword, api_key, CardNumber, Cvv and Ssn.

A short word, such as Pin, counts only as a whole word of the name: SimPin is sensitive, and Shipping is not. A longer word, such as password, secret or token, counts anywhere in a name, also in a name written in one piece. So newpassword, SecretaryName and TokenCount are all sensitive. A field left out in this way disappears from the form with no error: check the parameter that the model reads, and include the fields that are not secrets.

The runner in the page checks the fields too. No step writes a password field, or a field whose autocomplete is current-password, new-password, one-time-code, cc-number or cc-csc. A form writes such a field only when you include it with IncludeSensitive. Otherwise the model is told that the user must fill it in. A recipe never writes such a field.

A grid is a table of rows, written by hand or rendered by a QuickGrid. Its key is a property of the row that tells the rows apart: a text, a whole number, a Guid or an enum. The columns, including the key, are the properties with a getter of a simple type:

TicketRow.cs
// A row of the grid: the key is Id, and every column has a getter
public sealed record TicketRow(
    int Id, string Title, string Customer, TicketPriority Priority);

In a table written by hand, each part of the grid carries a data-mentor-id:

TicketsPage.razor
@page "/support/tickets"
@inject IMentorPageContext PageContext
@inject IJSRuntime JS
@implements IDisposable

<input data-mentor-id="tickets.filter" @bind="_filter" @bind:event="oninput" />
<table>
    <thead>
        <tr>
            <th>Number</th>
            <th data-mentor-id="tickets.sort.title" aria-sort="@AriaSort("title")"
                @onclick="@(() => Sort("title"))">Title</th>
            <th data-mentor-id="tickets.sort.priority"
                aria-sort="@AriaSort("priority")"
                @onclick="@(() => Sort("priority"))">Priority</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var t in Shown)
        {
            <tr data-mentor-id="tickets.row">
                <td data-mentor-id="tickets.cell.id">@t.Id</td>
                <td>@t.Title</td>
                <td>@t.Priority</td>
                <td>
                    <button data-mentor-id="tickets.open"
                            @onclick="@(() => Open(t))">Open</button>
                </td>
            </tr>
        }
    </tbody>
</table>

@code {
    // _filter, Shown, Sort, AriaSort and Open are your page's own code
    protected override void OnInitialized()
    {
        PageContext.SetPageName("Tickets")
            .RegisterGrid<TicketRow>("tickets", "The open tickets", JS,
                t => t.Id,
                o => o.Sortable(nameof(TicketRow.Title),
                                nameof(TicketRow.Priority)));
        PageContext.SignalReady();
    }

    public void Dispose() => PageContext.Clear("Tickets");
}
Partdata-mentor-id
Each row"<grid>.row"
The key's cell, inside a row"<grid>.cell.<key>"
What opens a row, inside it"<grid>.open"
The filter field"<grid>.filter"
The header that sorts by a column"<grid>.sort.<column>"

The model gets up to three actions:

  • open_tickets_row({ key }) opens the row whose key cell shows the key, as the page shows it: it clicks the part of the row that opens it. When the row is not shown, the action first writes the key in the grid's filter. Then it scrolls the container of the rows, so that a grid that draws its rows only as they scroll into view draws the rows further down. The filter keeps the key afterwards, so the grid stays filtered. The action does not go through the pages of a paged grid: give such a grid a filter that finds a row by its key.
  • sort_tickets({ column, descending? }) clicks the header of the column until its aria-sort, or the aria-sort of the th that holds it, shows the order that the model asked. It clicks three times at most. A header without aria-sort counts as not sorted, so a table that marks only the header it is sorted by works. If a header still has no aria-sort after a click, its order cannot be read: the step stops there, and the model is told so. The columns are the columns of a simple type that are not sensitive, or the ones that you name with Sortable. With Sortable() and no column, the model gets no sort_ action.
  • filter_tickets(text) writes the text in the filter field, as the user would type it, and an empty text clears it.

A grid has a filter by default. When the page has no filter field, set o => o.Filter = false. The model then gets no filter_ action, and opening a row that is not shown scrolls the rows. With Filter left on and no filter field, filter_ always fails. Opening a row that is not already shown fails too, because the filter is tried first.

Nothing of the rows goes back to the model. Each action answers that it was done, or that it was not done and why. Rows and cells inside data-mentor-exclude are never read.

A column is sensitive by the same signs as a form's field. The grid does not sort by a sensitive column unless you include it with IncludeSensitive, and RegisterGrid throws when Sortable names it without including it. A sensitive column is never the key, included or not, because the model would have to write its value to open a row: RegisterGrid throws then too.

A QuickGrid renders its rows and headers itself, so you cannot give them an attribute. Give them selectors of your own with Selector. Its first argument is the part: what follows "<grid>." in the data-mentor-id of the table above, such as row or sort.customer. The example shows only the registration: the list after it says how to write the markup of the QuickGrid.

OrdersPage.razor
@code {
    protected override void OnInitialized() =>
        PageContext.RegisterGrid<OrderRow>("orders", "The orders", JS,
            r => r.Id, o =>
            {
                o.Filter = false;   // the page has no filter field
                o.Sortable(nameof(OrderRow.Customer), nameof(OrderRow.Total))
                 // Selector(part, CSS selector): part is what follows "orders."
                 .Selector("row", ".orders tbody tr")
                 .Selector("sort.customer", ".orders th:nth-child(2) .col-title")
                 .Selector("sort.total", ".orders th:nth-child(3) .col-title");
            });
}
  • The rows and headers. Give the grid's table a class of your own with the Class parameter of QuickGrid, here orders, and point the selectors at it. QuickGrid writes aria-sort on its headers, so sorting works.
  • The key and the open button. Write the key's cell as a TemplateColumn with a <span data-mentor-id="orders.cell.id">, and the open button as another TemplateColumn with data-mentor-id="orders.open". Those two need no selector.
  • The columns it sorts by. A TemplateColumn sorts only with its SortBy. Here the key's column has none, so Sortable names the columns that QuickGrid sorts, each with the selector of its header.
  • A grid with Virtualize renders its rows as they scroll into view. Opening a row scrolls the grid until the row is there.

A form or a grid that does not match the page fails, and MentorAgent never guesses. A mistake in the registration throws an exception in your page when it opens:

  • a name that is not a valid tool name: letters, digits, _ and -, with the action's name at most 64 characters;
  • a name in the options that is not a field, a column or a part, or Selector("filter", …) with Filter = false;
  • a form with no field;
  • a grid whose key is not a text, a whole number, a Guid or an enum, or whose key is sensitive;
  • a sensitive column in Sortable.

When the model calls the action on Blazor Server or .NET MAUI Blazor Hybrid, it reads one of these results. On WebAssembly, see Where it runs.

What happensWhen
Nothing runs, and the model reads whyA value that its field does not take; a column that the grid does not sort by; a key of the wrong type
The action stops at a field, and the model reads whichA field that is not in the page; a field that is hidden, disabled or inside data-mentor-exclude; a password field; a field that is not the kind of element that its type needs; or an option with no such label. The fields before it stay filled
The row is not openedNo row has the key, after the filter and scrolling: the model reads that no row has it, never the rows. Or the filter field or the open button is missing, hidden or disabled
The grid is not sortedThe header is missing, hidden or disabled; it does not say its order with aria-sort; or the order is another after three clicks

Check your pages against these: the action is offered as soon as the page registers it, also when a data-mentor-id is missing.

The steps run in the page, through the IJSRuntime that you pass, with the same code that runs recipes.

  • Blazor Server and .NET MAUI Blazor Hybrid. The page runs in the process of the turn. The model waits for the browser's answer, and reads that the action was done or why it was not.
  • Blazor WebAssembly. The page runs in the browser, and the hub asks the client to run the action, as for every UI action of a WebAssembly client. Unlike a recipe, the model does not wait for the browser's answer: it reads that the action was done as soon as the request is sent. It does not learn whether a field was missing or a row was found. A value of the wrong type is refused in the client, and the model does not read the refusal.
  • React, Angular and other front ends. There are no ready-made actions for forms and grids. Register UI actions of your own, or run recipes in your front end.

The actions of a form and a grid are UI actions of the page, and go through the gate as any UI action:

  • your action policies are asked when the action is offered and when it is called, with Kind UI and the page's name;
  • a policy can keep the action out of the turn, refuse the call, or ask the user to confirm it;
  • your action observers receive its decisions, and Stop reaches it.

A UI action asks for no confirmation and no role of its own. Filling a form changes nothing until the user, or an action of yours, sends it.

The rules are form.fill, form.sensitive, grid.open, grid.filter, grid.sort and grid.sensitive, in ACTION-RULES.md in the MentorAgent repository (external site). Each rule has a name that never changes, and a test in the library.

  • Recipes — Give the agent procedures on your pages, approved outside your code: sources, steps, rows of a grid, limits, and how each recipe is governed.
  • Ruoli, conferma e governance — Ruoli e approvazione human-in-the-loop per i tool di un agente AI in .NET: controlli nel codice, non nel prompt, su ogni canale, e cosa resta a te.
  • Action policies and observers — The types that let your code decide on each action, record every decision of the gate, know who confirmed a call, and list the actions.
  • MentorAgent 1.5.0 release notes — What's new in MentorAgent 1.5.0: pages known from your routes, a scan of the pages, recipes, forms and grids as UI actions, and the cost per agent and user.