Blazor服务器端oninput事件导致错误

我正在使用带有信用卡号的表单构建示例组件。我试图将oninput事件添加到InputText组件,一旦附加该组件便无法正常运行。没有事件,表单将正常运行。不管事件提供的方法做什么,它始终无法正常运行。

代码:

<microsoft.AspNetCore.Components.Forms.EditForm Model="@card" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div>
        <div>
            <p>
                <label for="ccNumberId">Debit or Credit Card Number</label><br />
                <InputText id="ccNumberId" @bind-Value="card.Number" 
                     @oninput="@(e => FormatCreditCardNumber())"       /><br />
                @numberFormat
            </p>
            <p>
                <label for="ccYearId">Expiration Year</label><br />
                <InputText id="ccYearId" @bind-Value="card.ExpYear" />
            </p>
            <p>
                <label for="ccMonthId">Expiration Month</label><br />
                <InputText id="ccMonthId" @bind-Value="card.ExpMonth" />
            </p>
            <p>
                <label for="ccCvcId">CVC</label><br />
                <InputText id="ccCvcId" @bind-Value="card.Cvc" />
            </p>
        </div>
    </div>
    <button type="submit">Submit</button>
</microsoft.AspNetCore.Components.Forms.EditForm>

@code {
    string numberFormat;

    private StripeChargeModel card = new StripeChargeModel();

    protected override void OnInitialized()
    {
    }

    private void HandleValidSubmit()
    {
        JSRuntime.InvokeVoidAsync("showOnToast","#paymentToast");
    }

    private void FormatCreditCardNumber()
    {
        if (card.Number.Length == 4)
        {
            numberFormat = String.Empty;
            numberFormat = card.Number + "-";
        }
    }
}
yaobaoshun 回答:Blazor服务器端oninput事件导致错误

请注意,您是通过@bind-Value="card.Number"而不是@bind-value:oninput绑定值。当值更改(即@bind-Value事件)时,onchange伪指令绑定值。并且 oninput 事件在之前 onchange 触发:当第一个按键事件触发时,card.Numbernull,因为@onchange事件尚未到达。

为了解决该问题,您需要在检查card.Number时防止nullcard.Number.Length == 4,否则在第一次按键时它将抛出System.NullReferenceException 事件触发:

private void FormatCreditCardNumber()
{
    if (card.Number.Length == 4)
    if (card.Number?.Length == 4)
    {
        numberFormat = String.Empty;
        numberFormat = card.Number + "-";
    }
}
本文链接:https://www.f2er.com/3127618.html

大家都在问