Dynamic Text Field Creation with Values in Blazor App

点点圈 提交于 2020-01-05 07:23:52

问题


Expected Output Output

 @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;
    }

}
  • In this Code am trying to get Dynamic Text box with values. Don't know how to hold Dynamic text box values. Here i used two Way data Binding @bind-value.Is there any other way to solve this issue. *

回答1:


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("");
    }

}

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



来源:https://stackoverflow.com/questions/59027615/dynamic-text-field-creation-with-values-in-blazor-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!