Blazor App中带有值的动态文本字段创建 [英] Dynamic Text Field Creation with Values in Blazor App
本文介绍了Blazor App中带有值的动态文本字段创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
预期输出
推荐答案
重点是绑定到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时始终是一个很好的实践.请参阅此答案,并注意[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 App中带有值的动态文本字段创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文