Skip to content

Instantly share code, notes, and snippets.

@YARG
Created February 4, 2025 16:48
Show Gist options
  • Save YARG/ad0c263e76a225eaf28dff90d8248dac to your computer and use it in GitHub Desktop.
Save YARG/ad0c263e76a225eaf28dff90d8248dac to your computer and use it in GitHub Desktop.
Basic MudBlazor MudTable Example with List Binding
@page "/ListExample"
@using System.Collections.Generic
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web
<MudCard Class="pa-4">
<MudCardContent>
<MudStack Row="true">
<MudTextField @bind-Value="_newItem" Label="Enter item" Adornment="Adornment.Start" @ref="TextFieldRef" />
<MudButton StartIcon="@Icons.Material.Filled.Add" OnClick="AddItem" Color="Color.Primary" Variant="Variant.Filled">Add</MudButton>
</MudStack>
<MudTable Items="Items" Hover="true">
<HeaderContent>
<MudTh>Item</MudTh>
<MudTh>Action</MudTh>
</HeaderContent>
<RowTemplate Context="item">
<MudTd>@item</MudTd>
<MudTd>
<MudButton StartIcon="@Icons.Material.Filled.Delete" OnClick="() => RemoveItem(item)" Color="Color.Primary" Variant="Variant.Filled" Size="Size.Medium">delete</MudButton>
</MudTd>
</RowTemplate>
</MudTable>
</MudCardContent>
</MudCard>
@code {
private List<string> Items = new() { "Item 1", "Item 2", "Item 3" };
private string _newItem = string.Empty;
private MudTextField<string> TextFieldRef = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await TextFieldRef.FocusAsync();
}
}
private void AddItem()
{
if (!string.IsNullOrWhiteSpace(_newItem))
{
Items.Add(_newItem);
_newItem = string.Empty;
// Refocus after adding an item
TextFieldRef.FocusAsync();
}
}
private void RemoveItem(string item)
{
Items.Remove(item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment