Reputation: 12454
I created a sample Blazor project. The scaffolding has two examples, (1)calling a C# method that exists IN the web page = counter, (2)calling a server method at the BEGINNING of the web page initialisation = weather table. But not any example for calling a server method and get result when a button is clicked. Is that possible?
For example, can I add a method like this to the "WeathrForecastService.cs":
public int Add(int a, int b)
{
return a + b;
}
and like the "counter" example, add a button on the page, and when the button is clicked, display the result of it:
@page "/fetchdata"
@using BlazorApp1.Data
@inject WeatherForecastService ForecastService
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from a service.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<p>Current count: @[display the result of ForecastService.Add(1,2)]</p>
<button class="btn btn-primary" @onclick="[call ForecastService.Add(1,2)]">Click me</button>
}
@code {
WeatherForecast[] forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}
}
Upvotes: 4
Views: 4193
Reputation: 25350
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>
Upvotes: 5