74
votes

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?

4
it looks like you need to have a return type on you function, try changing void to string - DalTron
@DalTron I changed void to string and added "return a" - now onClick buttons show on console ReferenceError: a is not define and after refreshing page it shows 579 which is 123+456 But Why? - Axelly
Does it work with a lambda? @for (int i = 0; i < 10; i++) { <button onclick="@(e => test(i, 5 * i))">Check</button> } - bcwhims
@bcwhims Perfectly! Please write it as an answer! - Axelly

4 Answers

136
votes

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

I try this and worked

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

like

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

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

9
votes

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

@onclick = "@(() => test(i, 5*i))"
1
votes
<input type="button" @onclick="@(() => functionname(paramvalue))" class="....." value="DoSomething" />