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

我与影子孤独终老i 提交于 2020-01-24 21:01:06

问题


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);
    }
}

回答1:


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>


来源:https://stackoverflow.com/questions/58212051/blazor-call-a-server-method-when-a-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!