【问题标题】:Dynamic Text Field Creation with Values in Blazor App在 Blazor 应用程序中使用值创建动态文本字段
【发布时间】:2020-03-20 11:54:04
【问题描述】:

Expected OutputOutput

 @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。有没有其他方法可以解决这个问题。 *

【问题讨论】:

  • 我将@functions更改为@code。结果:如果我输入一个文本框,由于双向数据绑定,它会在动态添加时反映在所有文本中。
  • 使用预期输出图像更新代码
  • 我已经更新了我的答案以反映图像输出...

标签: dynamic data-binding textbox blazor


【解决方案1】:

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

@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]

【讨论】:

  • 现在我可以添加用户了,如何在提交数据时检索用户文本框值
  • 他们在userNames。至少在这个答案中。
  • 我们每次都在列表中添加空字符串,输入值后如何检索我们添加的每个文本框的数据。
  • 你说得对,目前还没有合适的 2 向绑定。
  • 添加了修复 (@bind) 和一个演示片来验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多