【发布时间】:2020-06-10 10:48:20
【问题描述】:
我想在循环中将值绑定到列表中的元素,但我找不到好的解决方案。
<EditForm Model="@dailyReport" OnValidSubmit="@SubmitDailyReport">
<p>
<label>Count: </label>
<InputNumber min="1" id="numberOfEffects" @bind-Value="numberOfEffects" />
</p>
@{
for (int i = 1; i <= numberOfEffects; i++)
{
if (effects.Count < i)
{
effects.Add("");
}
if (effects.Count > i)
{
effects.RemoveAt(effects.Count - 1);
}
string concatId = "effect" + i.ToString();
<p>
<label for="@concatId">@i</label>
<InputText id="@concatId" @bind-Value="effects.ElementAt(i-1)" />
</p>
}
}
//rest code
</EditForm>
当我尝试将值绑定到列表中的元素时,出现错误:
- 错误 CS0131:分配的左侧必须是 变量、属性或索引器错误
- 错误 CS1662:无法转换 lambda 表达式到预期的委托类型,因为一些返回 块中的类型不能隐式转换为委托 返回类型
我想知道是否有任何可能的方法将数据绑定到集合。我需要它,因为我的模型具有 List 类型的属性。在我的输入表单中,我希望允许添加用户需要的任意数量的字符串。
编辑:
@code
{
private DailyReport dailyReport = new DailyReport();
private List<string> effects = new List<string>();
}
我也尝试在 foreach 循环中执行此操作,但显示了另一个错误: 无法分配给“效果”,因为它是“foreach 迭代变量”
foreach (var effect in effects)
{
index++;
Console.WriteLine(index);
string concatId = "effect" + index.ToString();
<p>
<label for="@concatId">@index</label>
<InputText id="@concatId" @bind-Value="effect" />
</p>
}
【问题讨论】:
-
我在@code 部分声明它们
-
请尝试修改您的代码 sn-p 以使其最小化,另请参阅stackoverflow.com/help/minimal-reproducible-example
标签: c# html razor blazor asp.net-core-3.0