在 Blazor 应用程序中使用值创建动态文本字段
Dynamic Text Field Creation with Values in Blazor App
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;
}
}
- 在此代码中,我试图获取带有值的动态文本框。不知道如何保存动态文本框值。这里我使用了两种方式的数据绑定 @bind-value.Is 还有其他方法可以解决这个问题。 *
重点是绑定到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 时始终是一个很好的做法。请参阅 并注意 [j]
。
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;
}
}
- 在此代码中,我试图获取带有值的动态文本框。不知道如何保存动态文本框值。这里我使用了两种方式的数据绑定 @bind-value.Is 还有其他方法可以解决这个问题。 *
重点是绑定到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 时始终是一个很好的做法。请参阅 [j]
。