在 Blazor 应用程序中使用值创建动态文本字段 [英] Dynamic Text Field Creation with Values in Blazor App

查看:13
本文介绍了在 Blazor 应用程序中使用值创建动态文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

预期输出 输出

 @page "/"

@using UDemo.Data


@for (int i = count; i >= 1; i--)
{
    <div class="row">
        <input type="text" @bind-value="@text_val" /> <p>@i</p><p>@count</p>

    </div>

}
<div class="row">

    <button @onclick=@(() => Increment())>Add User</button>

</div>


@code {
    private List<string> listItems = new List<string>();
    private string newItem;
    public string select_val;
    public string text_val;
    public int count = 1;
    public void Increment()
    {
        count = count + 1;
    }

}

  • 在此代码中,我试图获取带有值的动态文本框.不知道如何保存动态文本框值.这里我使用了两种方式数据绑定@bind-value.有没有其他方法可以解决这个问题.*
  • 推荐答案

    重点是绑定到userNames[i].这就是为什么 foreach() 在这里不起作用的原因.

    The point is to bind to userNames[i]. And that is why a foreach() won't work here.

    @page "/"
    
    <ul>
        @for (int i = 0; i < userNames.Count; i++)
        {
            int j = i;  // copy i to be safe
    
            <li>
            <input type="text" @bind="@userNames[j]"  />
            </li>
        }
    </ul>
    
    <button @onclick="AddUser">Add User</button>
    
    
    @*to verify  the binding*@
    @foreach (string userName in userNames)
    {
        <p>@userName</p>
    }
    
    @code
    {
    
        List<string> userNames = new List<string>() { "first user" };
    
        void AddUser()
        {
            userNames.Add("");
        }
    
    }
    

    这里需要 j = i 部分,并且在使用 for 循环和 Blazor 时始终是一个好习惯.请参阅 this answer 并注意 [j].

    The j = i part is needed here and always a good practice when working with for loops and Blazor. See this answer and do note the [j].

    这篇关于在 Blazor 应用程序中使用值创建动态文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆