【问题标题】:Blazor: Call a server method when a button is clicked?Blazor:单击按钮时调用服务器方法?
【发布时间】:2020-02-01 08:31:08
【问题描述】:

我创建了一个示例 Blazor 项目。脚手架有两个示例,(1) 调用网页中存在的 C# 方法 = 计数器,(2) 在网页初始化 = 天气表的 BEGINNING 处调用服务器方法。但没有任何示例用于调用服务器方法并在单击按钮时获取结果。这可能吗?

例如,我可以在“WeathrForecastService.cs”中添加这样的方法吗:

    public int Add(int a, int b)
    {
        return a + b;
    }

和“计数器”的例子一样,在页面上添加一个按钮,当按钮被点击时,显示它的结果:

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

【问题讨论】:

    标签: asp.net-core blazor


    【解决方案1】:

    调用服务器方法并在单击按钮时获取结果。这可能吗?

    是的。如果您使用的是 Blazor 服务器端,则将通过 SignalR 在后台调用服务器端方法。

    类似于我们在 Angular/React 中的方式,为了显示结果,我们需要创建一个 _sum 字段来缓存结果,以便我们以后可以显示/更改它:

    @code {
        private int _sum;
    }
    

    并更改您的onclick 如下:

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

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 1970-01-01
      • 2023-02-21
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多