BLAZOR : Onclick event fired automatically when with component base class model

Viewed 1606

I am having a razor page as below. its inheriting the PaymentBase class that is having the code behind codes..

@page "/payment"
@inherits PaymentBase

<h1>Payments</h1>

<button class="btn btn-primary" onclick="@GetList()">List all payments</button>

The GetList function is fired automatically once the page is rendered and not on the click event.. any help please ??

2 Answers

You need to pass a function, not call the function.

<button class="btn btn-primary" @onclick="GetList">List all payments</button>

By doing @onclick="GetList" you pass a function to onclick, by doing @onclick="GetList()" you are calling GetList and passing the return of GetList() to the onclick.

Also don't forget to add @ before the onclick.

onclick="@GetList()"

The above code is executed when your component is being rendered because the instruction @GetList() is evaluated to execution of GetList the result of which is assigned to the onclick attribute of the button element.

Note: onclick is an attribute of the button element, but @onclick is a compiler directive attribute instructing the compiler to create an EventCallback 'delegate' which encapsulates the method whose name provided as value to this attribute.

Always use the pattern: @onclick="<MethodName>"

Note that the following code is legitimate, but not recommended as it combines C# and JavaScript unnecessarily: onclick="window.prompt('Enter you name...')"

Hope this helps...

Related