ataraxia
ataraxia

Reputation: 1171

How to add onclick with parameter to button in Blazor?

I have the following code in a Blazor server-side app:

<div class="table-responsive">
    <table class="table">
        <thead>
            <tr>
                <th>Email</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var applicationUser in ApplicationUsers)
            {
                string userId = applicationUser.Id;
                Guid? personId = applicationUser.PersonId;

                <tr>
                    <td>@applicationUser.Email</td>
                    <td>@applicationUser.PersonName</td>
                    @if (personId != null)
                    {
                        <td>
                            <button class="btn btn-block btn-primary" @onclick="() => ShowEditPersonDialog(personId)" style="color: rgb(255, 255, 255); background-color: rgb(49, 56, 215);" @type="button">Edit Person</button>
                        </td>
                    }
                </tr>
            }
        </tbody>
    </table>
</div>

However this:

@onclick="() => ShowEditPersonDialog(personId)"

...doesn't work. As it is above the component loads up until the first button on the first row (there are 4 users - 4 rows should load) then the button doesn't render properly and an unhandled exception is thrown:

Blazor application exception

I've tried:

How the hell do I write this thing?? I simply want a button to pass through the relevant personId for the given row to the ShowEditPersonDialog method.

Upvotes: 5

Views: 5237

Answers (1)

Umair
Umair

Reputation: 5501

Change your button to this - remove the @ from type="button" and use @onclick="@(() => ShowEditPersonDialog(personId))"

<button class="btn btn-block btn-primary" 
    @onclick="@(() => ShowEditPersonDialog(personId))" 
    style="color: rgb(255, 255, 255); background-color: rgb(49, 56, 215);" 
    type="button">Edit Person</button>

Its also good to move your inline button css styles to a class in a css file so the HTML markup is cleaner to read :)

Upvotes: 11

Related Questions