问题描述
我尝试捕获Blazor(ServerSide)中InputText的文本更改,然后调用一个异步方法来检查输入是否正确的优惠券代码.
I try to capture text changes of InputText in Blazor (ServerSide) and then call a async method to check if input is correct coupon code or not.
HTML:
<EditForm Model="@Basket" OnValidSubmit="@CommitBasket">
Gutscheincode
<InputText class="coupon-input checkout-control pristine untouched"
@bind-Value="CouponCode"
@onchange="CouponCodeChanged">
</InputText>
@CouponText
</EditForm>`
但是未引发CouponCodeChanged-OnKeyUp没用,因为在该状态下文本值未更改...
But The CouponCodeChanged isn't raised - OnKeyUp is not useful because the Text Value isn't changed at that state...
这是C#方法:
public async Task CouponCodeChanged(ChangeEventArgs args)
{
using var client = ClientFactory.CreateClient();
var result = await ApiCalls.GetCouponCodeData(client, AppState.BaseUrl, 2, CouponCode);
CouponText = result== null ? "NOT FOUND" : $"exists:{result.Exists} amount:{result.Amount}";
}
有人有提示或想法如何方便地解决该问题吗?
Has anyone a hint or idea how to solve that in a convinient way?
谢谢!
推荐答案
InputText
组件没有 onchange
事件,但没有 ValueChanged
.
但是,如果要预订此事件,则需要传递 ValueExpression
,这并不容易.我发现预订此事件最简单的方法是覆盖 InputText
组件.
InputText
component doesn't have a onchange
event but ValueChanged
.
However, if you want to subscribe to this event you need to pass a ValueExpression
and it's not easy.The easiest I found to subscribe to this event is to override the InputText
component.
CouponComponent.razor
@inherits InputText
<InputText class="coupon-input checkout-control pristine untouched"
ValueExpression="ValueExpression" Value="@Value" ValueChanged="OnValueChanged" />
@code {
[Parameter]
public EventCallback<string> CouponValueChanged { get; set; }
private async Task OnValueChanged(string value)
{
await ValueChanged.InvokeAsync(value);
using var client = ClientFactory.CreateClient();
var result = await ApiCalls.GetCouponCodeData(client, AppState.BaseUrl, 2, CouponCode);
var coupon = result == null ? "NOT FOUND" : $"exists:{result.Exists} amount:{result.Amount}"
await CouponValueChanged.InvokeAsync(coupon);
}
}
用法
<EditForm Model="@Basket" OnValidSubmit="@CommitBasket">
Gutscheincode
<CouponComponent @bind-Value="CouponCode"
@CouponValueChanged="CouponCodeChanged">
</InputText>
@CouponText
</EditForm>
@code {
private void CouponCodeChanged(string coupon)
{
CouponText = coupon;
StateHasChanged();
}
}
这篇关于当TextChanged时Blazor InputText调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!