Blazor如何将参数传递给onclick函数? [英] Blazor how to pass arguments to onclick function?

查看:977
本文介绍了Blazor如何将参数传递给onclick函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使按钮onclick功能需要一些输入.

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

稍后我想在for循环中创建这些按钮

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>
}

我该如何实现?

推荐答案

尝试使用lambda.您将onclick绑定到函数的结果,而不是函数本身.

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>
}

这篇关于Blazor如何将参数传递给onclick函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆