Blazor: How to bind table row data to button click

PeterMilovcik - Feb 26 '20 - - Dev Community

If you ever wondered how to bind the button in the table row to the item from the collection. Here is little help on how to do that:

Table



@page "/somecomponent"

<h3>Some Component</h3>

<table class="table">
    <thead>
    <tr>
        <th>Name</th>
        <th>Edit</th>
        <th>Remove</th>
    </tr>
    </thead>
    <tbody>
    @foreach (var item in items)
    {
        <tr>
            <td>@item.Name</td>
            <td><button @onclick="@(() => Edit(item))">Edit</button></td>
            <td><button @onclick="@(() => Remove(item))">Remove</button></td>
        </tr>
    }
    </tbody>
</table>

@code {

    List<Item> items;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        // Initialize collection of items get it from some service or context
        items = new List<Item>
    {
            new Item {Id = 1, Name = "Item1"},
            new Item {Id = 2, Name = "Item2"},
            new Item {Id = 3, Name = "Item3"},
        };
    }

    void Edit(Item item) => Console.WriteLine($"Edit item: {item.Name}");
    void Remove(Item item) => Console.WriteLine($"Remove item: {item.Name}");

    class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}



Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .