[英]How to add dynamic checkboxes in a Blazor-server app that use a list of booleans?
To clarify my question more I'll first show you add a checkbox using the blazor component library I'm using:为了进一步澄清我的问题,我将首先向您展示使用我正在使用的 blazor 组件库添加一个复选框:
<MudCheckBox @bind-Checked="@Basic_CheckBox1"></MudCheckBox>
@code{
public bool Basic_CheckBox1 { get; set; } = false;
}
the code above creates a checkbox and then toggles the boolean Basic_CheckBox1 to true or false based on if the checkbox is checked or not.上面的代码创建一个复选框,然后根据复选框是否选中将 boolean Basic_CheckBox1 切换为 true 或 false。 here is my code
这是我的代码
@for (int i = 0; i < checkboxNames.Count; i++)
{
<MudCheckBox @bind-Checked="@checkboxBools[i]" Label="@checkboxNames[i]"></MudCheckBox>
}
this code works until I check or uncheck my created checkboxes, then I get the index out of range error, how can I fix this?此代码有效,直到我选中或取消选中我创建的复选框,然后我得到索引超出范围错误,我该如何解决这个问题? I need to use a list of booleans because I don't know how many checkboxes I will need until runtime, if there is any other solution please let me know.
我需要使用布尔值列表,因为在运行之前我不知道需要多少个复选框,如果有任何其他解决方案,请告诉我。
Think of it like the bind isn't done there and then in the loop, but later.把它想象成绑定不是在那里完成,然后在循环中完成,而是稍后完成。 By the time the bind comes to be done,
i
is off the end of the array Length, having been incremented repeatedly.到绑定完成时,
i
已超出数组 Length 的末尾,并且已重复递增。 Instead, you can save the current value of your loop variable i
into another variable, then use that other variable in your bind:相反,您可以将循环变量
i
的当前值保存到另一个变量中,然后在绑定中使用该其他变量:
@for (int i = 0; i < checkboxNames.Length; i++)
{
var x = i;
<MudCheckBox @bind-Checked="@checkboxBools[x]" Label="@checkboxNames[i]"></MudCheckBox>
}
checkBoxBools should be an array/list that is the same length (initalized to have the same number of elements as) checkBoxNames.. For example: checkBoxBools 应该是一个长度相同的数组/列表(初始化为与 checkBoxNames 具有相同数量的元素)。例如:
string[] checkboxNames = new string[]{"a","b","c"};
bool[] checkboxBools = new bool[3];
Or, if something else is providing a variable number of names:或者,如果其他东西提供了可变数量的名称:
checkboxNames = context.People.Select(p => p.Name).ToArray();
checkboxBools = new bool[checkBoxNames.Length];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.