Calling Function from Generated Button in Blazor

Calling function from generated button in Blazor

I guess you should add a local variable to your loop as follows:

@for (int i = 0; i < Buttons.Count; i++)
{
var local = i;
<button type="button" class="btn btn-primary btn-lg" style="margin:10px" onclick="@((ui) => ButtonClicked(local))">@Buttons[i]</button>
}

This is a standard C# behavior, not related to Blazor, where the lambda expression @((ui) => ButtonClicked(i)) has access to a variable and not to its value. You've got to define a variable which is local to your loop, otherwise your lambda expression always calls ButtonClicked(i) and i equals 3 when the loop ends.

Hope this helps...

Blazor : call a method without button click


<p> Hello you @HelloConsole() </p>

Says put the output from the method HelloConsole() here. But HelloConsole returns a void - exactly what the error says - which the renderer can't handle.

This works:

protected string HelloConsole()
{
Console.WriteLine("Hello");
return "I just wrote to the console";
}

Add on to answer:

To execute some code when loading the component:

protected override void OnInitialized()
{
Console.WriteLine("Hello");
}
// or

protected override Task OnInitializedAsync()
{
Console.WriteLine("Hello");
return Task.CompletedTask;

}

Blazor: Call a server method when a button is clicked?


calling a server method and get result when a button is clicked. Is that possible?

Yes. If you're using Blazor Server Side, the server side method will be invoked via SignalR under the hood.

Similar to the way we do in Angular/React, in order to display the result, we need create a _sum field to cache the result so that we can display/change it later:

@code {
private int _sum;
}

And change your onclick as below:

<p>Current count: @this._sum</p>
<button class="btn btn-primary" @onclick="()=>this._sum= ForecastService.Add(1, 2)" >Click me</button>

In Blazor how to call a function at Page Load (event name)?

There are two main ways you can do this, and either will work. I tend to prefer the first, but the second also gets the job done.

The first way, is in your @code block, you can override the OnInitialized method. I use the async version as you can kick off your task and let the page basics load, and then it will refresh when it gets set up.

@code {

void SomeStartupMethod()
{
// Do Some Work
}

Task SomeStartupTask()
{
// Do some task based work
return Task.CompletedTask;
}

protected override async Task OnInitializedAsync()
{
SomeStartupMethod();
await SomeStartupTask();
}

This will do work on the page load, like an initial service call to populate data, filling in lists conditionally, whatever you need to do. BTW, a trick I found is that if you put await Task.Delay(1); as the first line of the OnInitializedAsync method body, it will break the remaining execution free from the page render, so you can get an initial and responsive page while the initial load is still processing in the background. Just something to get your page responsive faster.

The second way is to override the OnAfterRender method, which allows the page 1 full render and then executes. It also has a default input of bool firstRender that you can use as a condition for data loads and other things.

protected override void OnAfterRender(bool firstRender)
{
// execute conditionally for loading data, otherwise this will load
// every time the page refreshes
if(firstRender)
{
// Do work to load page data and set properties
}
}

The important thing to remember for this method is that it will execute any time the Blazor engine detects the need to refresh the UI, so use that firstRender parameter wisely.

Depending on what you need to do, different lifecycle methods can be useful at different times, and there are a few more I haven't touched on. For further info, take a look at the official docs. I've been able to get very far on my own just using what the docs have supplied, and this link will get you started at lifecycle methods.

Hope this helps!

How to call a function in a parent razor component from a child item in blazor?

There is a simple direct way by making the TableHeader typed as well.

Changes in TableTemplate.razor

  <thead>
<tr>@TableHeader(this)</tr>
</thead>

@code {
[Parameter]
public RenderFragment<TableTemplate<TItem>>? TableHeader { get; set; }

and then use it like

<TableTemplate Items="pets" >
<TableHeader Context="table">

<button @onclick="() => table.SortSourceList(/* args */)" />

</TableHeader>

<RowTemplate Context="pet">
...
</RowTemplate>
</TableTemplate>

Send dynamic parameters on click with Blazor

It's called 'capturing the loop variable', Google that. Lambda's and for-loops don't go so well together.

The quick fix is to make copies:

@for (int r = 0; r < 10; r++) {
int rr = r;
<div class="row">
@for (int c = 0; c < 10; c++) {
int cc = c;
<div class="box"><div class="inner" style="background-color: @(GetColor(r,c));" @onclick="() => ChangeColor(rr, cc)">@((r*10+c).ToString())</div></div>
}

blazor variable argument passing to onclick function

This is a classic problem, but slightly new in the context of Blazor.

You need to make a copy of i because otherwise the lambda "captures the loop variable". Capturing the copy is OK.

@for (int i = 0; i < 3; i++)
{
int localCopy = i;
<li> item @i <button onclick=@(() => clickItem(localCopy))>Click</button> </li>
}

Note that this is an issue with for() loops but not with foreach(), and only on the right hand side of a =>.



Related Topics



Leave a reply



Submit