Blazor 如何向 onclick 函数传递参数?

我想使按钮 onclick功能,采取一些输入。

<button onclick="@test(123, 456)">Check</button>


@functions
{
public void test(int a, int b)
{
Console.WriteLine(a + b);
}
}

但出于某种原因,它抛出了一个错误:

Argument "1": Cannot convert from void to string

之后,我想在 for 循环中创建这些按钮,比如

@for (int i = 0; i < 10; i++)
{
<button onclick="@test(i, 5 * i)">Check</button>
}

我怎么才能做到呢?

66454 次浏览

Try it with a lambda. You're binding the onclick to the result of the function rather than the function itself.

@for (int i = 0; i < 10; i++)
{
var buttonNumber = i;
<button @onclick="@(e => test(buttonNumber, 5 * buttonNumber))">Check</button>
}

At Sign on onclick specifies it's a C# function:

@onclick = "@(() => test(i, 5*i))"

I try this and worked

@onclick="(() => FunctionName(argument))"

like

@onclick="(() => GetDetail(item.UserId))"

Got idea from https://github.com/aspnet/AspNetCore/issues/15956 .

<input type="button" @onclick="@(() => functionname(paramvalue))" class="....." value="DoSomething" />

The following both input as well as button typed worked for me.

<td>
<input type="button" class="btn btn-primary" value="Delete"
@onclick="(() => this.DeleteTodoItem(todoItem.Id))"  />
</td>
<td>
<button class="btn btn-primary"
@onclick="(() => this.DeleteTodoItem(todoItem.Id))">Delete</button>
</td>