问题
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