Blazor how to pass arguments to onclick function?

假装没事ソ 提交于 2020-01-01 09:21:54

问题


I'd want to make button onclick function that takes some input.

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

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

But for some reason it throws an error:

Argument "1": Cannot convert from void to string

Later I'd want to create those buttons in for loop like

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

How can I achieve that?


回答1:


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++)
{
    <button @onclick="@(e => test(i, 5 * i))">Check</button>
}



回答2:


Ampersand on onclick specifies it's a C# function:

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


来源:https://stackoverflow.com/questions/54297711/blazor-how-to-pass-arguments-to-onclick-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!