Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor how to pass arguments to onclick function?

Tags:

c#

blazor

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?

like image 731
Axelly Avatar asked Jan 21 '19 21:01

Axelly


People also ask

How do you use onclick in Blazor?

Blazor will invoke GreetMe when the button is clicked, and the user will see a friendly (if somewhat unimaginative) greeting. Your onclick event handler can optionally accept a MouseEventArgs parameter which Blazor will automatically include when it invokes the handler.

How do you get the target element onclick event in Blazor?

Blazor does not have support to manipulate DOM elements directly, but we can still achieve it by using JavaScript interop. By creating a reference to an element, we can send it as a parameter to the JavaScript method via interop.


2 Answers

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> } 
like image 125
bcwhims Avatar answered Sep 29 '22 07:09

bcwhims


I try this and worked

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

like

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

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

like image 37
sami ullah Avatar answered Sep 29 '22 06:09

sami ullah