【问题标题】:Change label text on Input Box value change更改输入框值更改上的标签文本
【发布时间】:2021-03-04 09:11:36
【问题描述】:

我正在使用带有 ASP.NET Core 3.0 的 Blazor 框架。

我有一个输入框,我在它旁边添加了一个标签 HTML。当用户在输入框中输入 5 时,标签应显示计算值 5/2。即Input Box的值除以2。

在 Blazor 框架中,我不明白如何添加 jQuery。

代码是这样的:

                <div class="col-sm-4">
                    <div class="justify-content-center mb-2">
                        <input type="text" class="form-control form-control-sm border border-secondary" @bind="myModel.CarWeight[index]" />
                    </div>
                </div>
                @if (myModel.AppType == "LC" || myModel.AppType == "LN")
                {
                    decimal calcRes = Convert.ToDecimal(myModel.CarWeight[index]) / 2;
                    
                     <div class="col-sm-4">
                        <div class="justify-content-center mb-2">
                            <label class="col-form-label"><b>calcRes</b></label>
                        </div>
                    </div>
                }

请注意这一行:myModel.CarWeight[index]

页面加载时,会创建一个5行2列的入口表单。 5个输入框。当用户填写任何输入框时,我希望相应的标签显示计算。

【问题讨论】:

  • 请发布您的所有代码。
  • @enet 这是我写的完整的计算代码。由于其中包含官方信息,无法粘贴整个页面代码。
  • Je 可能想要添加您使用的 blazor,例如服务器端或 webassembly。当你有 blazor 时,你还使用 jquery 吗?

标签: c# asp.net-core blazor asp.net-core-3.1


【解决方案1】:

您可以更新特定事件的绑定值

@bind:event="oninput"

https://docs.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-5.0

你会得到这个非常简单的代码

@page "/"

<input type="number" @bind="inputVal" @bind:event="oninput" />
<label>@(Convert.ToDouble(inputVal)/2)</label>

@code{
    string inputVal = "0";
}

【讨论】:

  • 非常感谢。进行了一些调整。
【解决方案2】:

也许有人会想出更好的主意来实现你想要的,但目前你可以用 C# 代码(.NET 5.0.103)尝试这样的事情:


@page "/SampleComponent"

<input type="number" @bind="Operations[0].Input" @oninput="@( (input) => Calculate(input, 0))"/> 
<label>@Operations[0].Result</label>
<input type="number" @bind="Operations[1].Input" @oninput="@( (input) => Calculate(input, 1))"/> 
<label>@Operations[1].Result</label>

@code {

    public List<Operation> Operations = new List<Operation>();
    
    protected override void OnInitialized()
    {
        base.OnInitialized();
        Operations.Add(new Operation{Input = 0, Result = 0});
        Operations.Add(new Operation{Input = 0, Result = 0});
    }
    
    public void Calculate(ChangeEventArgs input, int id)
    {
        float result;

        if(float.TryParse((string)input.Value, out result))
        {
            Operations[id].Result = result/2;
        }
        else
        {
            Operations[id].Result = 0;
        }
    }

    public class Operation
    {
        public float Input { get; set; }
        public float Result { get; set; }
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多