Skip to content
IzzyBlazor

Enter all results ↑ ↓ move Esc close

FieldRepeater

Since 0.1.0-alpha.24
Rows of the same fields that people add and remove, such as invoice lines.

Use it inside a form for a list that's part of what's being filled in: an invoice's lines, a person's emergency contacts, price tiers. For records people browse, search and edit one at a time, use a DataGrid.

Invoice lines

Bind Items to the model's list with @bind-Items, and put one row's fields inside, bound to the row (the Context). The rows post with the form as a list, so the model gets them back. FieldRepeaterValue shows a value worked out from the row, such as the amount, and Footer goes beside Add.

Static

Preview

Items
$
Amount$600.00
$
Amount$300.00

Subtotal $900.00

Code

Usage.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="invoice-lines" OnValidSubmit="Save" Grow>
    <FormErrors />
    <FieldRepeater @bind-Items="Model!.Lines" NewItem="() => new Line()" Label="Items" AddText="Add item" MinItems="1" Context="line">
        <ChildContent>
            <TextField @bind-Value="line.Description" Label="Description" />
            <NumberField @bind-Value="line.Quantity" Label="Quantity" Width="Length.Rem(6)" />
            <NumberField @bind-Value="line.UnitPrice" Label="Unit price" Step="0.01" Width="Length.Rem(9)">
                <StartAddon>$</StartAddon>
            </NumberField>
            <FieldRepeaterValue Label="Amount" Width="Length.Rem(7)" Align="CellAlign.End">@line.Amount.ToString("C")</FieldRepeaterValue>
        </ChildContent>
        <Footer>
            <TextBlock Weight="FontWeight.Medium" TabularNums>Subtotal @Model.Lines.Sum(l => l.Amount).ToString("C")</TextBlock>
        </Footer>
    </FieldRepeater>
    <FormActions><Button Submit>Save invoice</Button></FormActions>
    @if (_saved)
    {
        <Alert Status="Status.Success">Saved @Model.Lines.Count lines, @Model.Lines.Sum(l => l.Amount).ToString("C") before tax.</Alert>
    }
</Form>

@code {
    [SupplyParameterFromForm(FormName = "invoice-lines")]
    private Invoice? Model { get; set; }

    private bool _saved;

    protected override void OnInitialized() => Model ??= new()
    {
        Lines = [new() { Description = "Website redesign, phase 2", Quantity = 1, UnitPrice = 600 }, new() { Description = "Hosting, 12 months", Quantity = 12, UnitPrice = 25 }],
    };

    private void Save() => _saved = true;

    public sealed class Invoice
    {
        public List<Line> Lines { get; set; } = [];
    }

    public sealed class Line
    {
        [Required(ErrorMessage = "Enter a description.")]
        public string? Description { get; set; }

        [Range(1, 999, ErrorMessage = "Enter a quantity from 1 to 999.")]
        public int Quantity { get; set; } = 1;

        [Display(Name = "Unit price"), Range(0, 1_000_000)]
        public decimal UnitPrice { get; set; }

        public decimal Amount => Quantity * UnitPrice;
    }
}

Static: Add and Remove post the form without reloading the page; focus goes to the new row.

Add this example to a page with the izzy CLI:

bash
izzy add component FieldRepeater --at <file>:<line>

Wide, the rows are a table with the fields' labels as headings; narrow, each row is a group with its fields one under another. It follows the repeater's own width, not the window's.

Each row's fields are checked with the form, and the error summary says which row: "Item 2, Description: Enter a description."

Always stacked

For rows with longer fields, such as contacts, set Layout to Stacked. ItemLabel names each row, here "Contact 1", and its Remove button says the same.

Static

Preview

Emergency contacts

Code

Stacked.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="emergency-contacts" OnValidSubmit="Save" Grow MaxWidth="32.Rem">
    <FieldRepeater @bind-Items="Model!.Contacts" Label="Emergency contacts" AddText="Add contact" Layout="RepeaterLayout.Stacked"
                   ItemLabel="@(i => $"Contact {i + 1}")" Context="contact">
        <TextField @bind-Value="contact.Name" Label="Name" />
        <TextField @bind-Value="contact.Relationship" Label="Relationship" />
        <TextField @bind-Value="contact.Phone" Label="Phone" Type="TextFieldType.Tel" />
    </FieldRepeater>
    <FormActions><Button Submit>Save contacts</Button></FormActions>
    @if (_saved)
    {
        <Alert Status="Status.Success">Saved @Model.Contacts.Count emergency contacts.</Alert>
    }
</Form>

@code {
    [SupplyParameterFromForm(FormName = "emergency-contacts")]
    private Profile? Model { get; set; }

    private bool _saved;

    protected override void OnInitialized() => Model ??= new()
    {
        Contacts = [new() { Name = "Ana Ruiz", Relationship = "Partner", Phone = "+1 415 555 0142" }],
    };

    private void Save() => _saved = true;

    public sealed class Profile
    {
        public List<Contact> Contacts { get; set; } = [];
    }

    public sealed class Contact
    {
        [Required(ErrorMessage = "Enter a name.")]
        public string? Name { get; set; }

        public string? Relationship { get; set; }

        [Required(ErrorMessage = "Enter a phone number."), Phone]
        public string? Phone { get; set; }
    }
}

Limits

MinItems and MaxItems keep the count in range: Remove goes at the minimum and Add at the maximum, and a form with fewer rows than the minimum doesn't save.

Static

Preview

Volume pricing
$
$

Code

Limits.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="price-tiers" OnValidSubmit="Save" Grow MaxWidth="36.Rem">
    <FormErrors />
    <FieldRepeater @bind-Items="Model!.Tiers" NewItem="() => new Tier()" Label="Volume pricing" AddText="Add tier" MinItems="1" MaxItems="4"
                   ItemLabel="@(i => $"Tier {i + 1}")" Context="tier">
        <NumberField @bind-Value="tier.UpToSeats" Label="Up to seats" />
        <NumberField @bind-Value="tier.PricePerSeat" Label="Price per seat" Step="0.01">
            <StartAddon>$</StartAddon>
        </NumberField>
    </FieldRepeater>
    <FormActions><Button Submit>Save pricing</Button></FormActions>
    @if (_saved)
    {
        <Alert Status="Status.Success">Saved @Model.Tiers.Count tiers.</Alert>
    }
</Form>

@code {
    [SupplyParameterFromForm(FormName = "price-tiers")]
    private Pricing? Model { get; set; }

    private bool _saved;

    protected override void OnInitialized() => Model ??= new()
    {
        Tiers = [new() { UpToSeats = 10, PricePerSeat = 12 }, new() { UpToSeats = 50, PricePerSeat = 10 }],
    };

    private void Save() => _saved = true;

    public sealed class Pricing
    {
        public List<Tier> Tiers { get; set; } = [];
    }

    public sealed class Tier
    {
        [Display(Name = "Up to seats"), Range(1, 10_000, ErrorMessage = "Enter a seat count from 1 to 10,000.")]
        public int UpToSeats { get; set; }

        [Display(Name = "Price per seat"), Range(0, 10_000)]
        public decimal PricePerSeat { get; set; }
    }
}

Details

How it works:

  • Static page: Add and Remove are submit buttons. The post keeps what was typed, changes the list, and redraws the form: the Form skips validation and its submit handlers.
  • Interactive page: Add and Remove change the list in C#.
  • Each row's fields are validated with the form (their [Required] and other attributes), as the form's own validator doesn't look inside a list.

Parts

Written inside FieldRepeater. The API page lists their parameters.

  • FieldRepeaterValue: a computed value in a FieldRepeater<T> row, such as a line's amount: shown under its own column heading in the table layout and with its label in the stacked one.

Mode support

What works in each mode, FieldRepeater
FeatureStaticInteractive
EverythingYesYes

Static: static server-side rendering, with no circuit and no WebAssembly. Interactive: Server, WebAssembly or Auto.

Accessibility

  • It's a fieldset named by Label; each row is a group named by ItemLabel ("Item 3").
  • Every field keeps its own label as its name in both layouts; the table's headings are only drawn, hidden from screen readers.
  • Remove is named for its row ("Remove Item 3"). After Add, focus goes to the new row; after Remove, to the row that took its place, else to Add.
  • The form's error summary names each row's messages: "Item 3, Quantity: Enter a quantity."

Parameters

FieldRepeater parameters
PropTypeDefault
@bind-ItemsThe rows: a list the form's model holds, such as an invoice's lines.List<TItem>?Required
ChildContentOne row's fields, for its item (the Context).RenderFragment<TItem>?
NewItemA new row's item for Add.Func<TItem>?
LabelNames the group of rows, such as "Items": drawn above them and read before each row.stringRequired
AddTextThe Add button's text, such as "Add item".string?"Add"
ItemLabelA row's name, from its index (from 0): heads it when stacked, names its group and its Remove button.Func<int, string>?"Item 1"
MinItemsThe fewest rows: Remove hides at this count, and a post with fewer is invalid.int0
MaxItemsThe most rows: Add hides at this count.int?
LayoutRepeaterLayout.Auto (the default): a table while the repeater is wide enough for its columns, else stacked.RepeaterLayoutRepeaterLayout.Auto
FooterBeside the Add button, under the rows: a subtotal.RenderFragment?
DisabledShows the rows read-only, with no Add or Remove.boolfalse
NonceThe nonce for its style element, when the page's CSP needs one.string?computed

See also

  • Fieldset: groups related fields under a legend.
  • Form: posts its fields on static pages and validates them live on interactive pages.
  • FormErrors: a summary of every validation message in the form.

Connection lost

Rejoining the server…