【问题标题】:Blazor server side oninput event causing errorBlazor 服务器端 oninput 事件导致错误
【发布时间】:2020-03-06 15:16:09
【问题描述】:

我正在构建一个带有信用卡号的表单示例组件。我正在尝试向 InputText 组件添加一个 oninput 事件,该组件在附加后无法正常运行。如果没有该事件,表单将正常运行。不管提供给事件的方法是什么,它总是无法正常运行。

代码:

<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 + "-";
        }
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-core-3.0 blazor-server-side


    【解决方案1】:

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

    为了解决这个问题,你需要在检查card.Number.Length == 4时防止card.Numbernull,否则它会在第一次击键时抛出System.NullReferenceException 事件触发:

    私人无效 FormatCreditCardNumber() { 如果 (card.Number.Length == 4) if (card.Number?.Length == 4) { numberFormat = String.Empty; numberFormat = card.Number + "-"; } }

    【讨论】:

    • 出于好奇,我将如何使用@bind-value:oninput 实现相同的操作?
    • @user1206480 对不起,“而不是..”的混淆词。我并不是建议你应该使用@bind-value:event='input',而是向你展示官方文档链接,其中描述了oninput 事件在击键时触发,bind-Value 实际上在值更改时绑定值。
    猜你喜欢
    • 2023-03-18
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2020-04-23
    • 2023-03-16
    • 2011-01-01
    • 2021-10-17
    相关资源
    最近更新 更多