Blazor:单击按钮时调用服务器方法吗? [英] Blazor: Call a server method when a button is clicked?
问题描述
我创建了一个示例Blazor项目.脚手架有两个示例,(1)调用网页中存在的C#方法=计数器,(2)在网页初始化=天气表的开始处调用服务器方法.但是,没有任何单击按钮时调用服务器方法并获得结果的示例.有可能吗?
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?
例如,我可以在"WeathrForecastService.cs"中添加这样的方法吗?
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);
}
}
推荐答案
调用服务器方法并在单击按钮时获取结果.有可能吗?
calling a server method and get result when a button is clicked. Is that possible?
是的.如果您使用的是Blazor服务器端,则将通过内部的SignalR调用服务器端方法.
Yes. If you're using Blazor Server Side, the server side method will be invoked via SignalR under the hood.
类似于我们在Angular/React中所做的那样,为了显示结果,我们需要创建一个_sum
字段来缓存结果,以便以后可以显示/更改它:
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;
}
并如下更改您的onclick
:
<p>Current count: @this._sum</p>
<button class="btn btn-primary" @onclick="()=>this._sum= ForecastService.Add(1, 2)" >Click me</button>
这篇关于Blazor:单击按钮时调用服务器方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!