[英]Blazor - Bind each element in @foreach loop to corresponding Array index
我的 Blazor 页面中有一个 @foreach 循环,它遍历 UserInput 类型的列表(UserInput 中的 var userInput)。
如果 userInput.IsInput 为假,那么我将显示一个
内容为 userInput.Text。
如果 userInput.IsInput 为真,我将显示一个字段并将其内容存储在 userInputBind[index] 中。
下面是我试过的代码:
@foreach (var userInput in myList)
{
if (userInput.IsInput)
{
<input @bind="userInputBind[index]"/>
if (index < 6) index++;
}
else
{
<p>@item.Text</p>
}
}
@code {
public List<UserInput> myList = new List<UserInput>
{
new UserInput { IsInput = false, Text = "One" },
new UserInput { IsInput = false, Text = "Two" },
new UserInput { IsInput = true, Text = "" },
new UserInput { IsInput = false, Text = "Four" },
new UserInput { IsInput = true, Text = "" },
new UserInput { IsInput = false, Text = "Six" }
};
public List<string> userInputBind = new List<string> { "", "" };
public int index;
public class UserInput
{
public bool IsInput { get; set; }
public string Text { get; set; }
}
}
当我在第一个输入字段中输入“string1”并在第二个字段中输入“string2”时,我希望列表包含{ "string1", "string2" }
。 相反,两个字符串都是“string2”。 我该如何解决这个问题? 任何帮助表示赞赏!
我想你想做的是:
@page "/"
@{index = 0;}
@foreach (var userInput in myList)
{
int loopindex = index;
if (userInput.IsInput)
{
<input @bind="myList[loopindex].Text"/>
}
else
{
<p>@userInput.Text</p>
}
index++;
}
@foreach (var userInput in myList)
{
<div class="m-2 p-2">
Value: @userInput.Text
</div>
}
@code {
public List<UserInput> myList = new List<UserInput>
{
new UserInput { IsInput = false, Text = "One" },
new UserInput { IsInput = false, Text = "Two" },
new UserInput { IsInput = true, Text = "" },
new UserInput { IsInput = false, Text = "Four" },
new UserInput { IsInput = true, Text = "" },
new UserInput { IsInput = false, Text = "Six" }
};
public int index;
public class UserInput
{
public bool IsInput { get; set; }
public string Text { get; set; }
}
}
我不明白的目的:
public List<string> userInputBind = new List<string> { "", "" };
这行得通。 它使用局部循环变量为每次循环迭代捕获“索引”,并为每次渲染重置index
。
它可能不是您问题的解决方案,但它回答了所提出的问题。
@page "/"
@{index = 0;}
@foreach (bool item in myList)
{
if (item)
{
int loopindex = index;
<div>
<input @bind="userInputBind[loopindex]"/>
</div>
index++;
}
}
@foreach(var value in userInputBind)
{
<div class="p-2">
Value = @value
</div>
}
@code {
public List<bool> myList = new List<bool> { false, false, true, false, true, false };
public List<string> userInputBind = new List<string> { "One", "Two" };
public int index;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.