[英]Binding the checked attribute of html input to boolean method return value in blazor
I am working on a blazor project currenty.我目前正在研究 blazor 项目。 In this project I need to add some default values to a list in my C# code.在这个项目中,我需要在我的 C# 代码中的列表中添加一些默认值。 The problem is that I can not find a way to bind a boolean method return value to the "checked" attribute of an input.问题是我找不到将 boolean 方法返回值绑定到输入的“已检查”属性的方法。
Code:代码:
I do have a list and I am adding an input (checkbox) field per entry in this list to my html:我确实有一个列表,并且我正在将此列表中的每个条目添加一个输入(复选框)字段到我的 html:
@foreach (ProfessionViewModel prof in Professions)
{
<div class="form-group m-1">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="@prof.Id"
@onchange="eventArgs => { ToggleProfessions(prof, eventArgs.Value); }" />
</div>
</div>
}
I cant find a way to bind the "checked" attribute to a method that checks if this item exists in an other list (SelectedProfessions list, defined in @code section).我找不到将“checked”属性绑定到检查该项目是否存在于其他列表(SelectedProfessions 列表,在@code 部分中定义)的方法的方法。
My list:我的列表:
public List<ProfessionViewModel> SelectedProfessions { get; set; } = new List<ProfessionViewModel>();
My boolean return method:我的 boolean 退货方法:
private bool CheckIfProfessionIsAssigned(ProfessionViewModel prof)
{
if (SelectedProfessions.Contains(prof))
return true;
return false;
}
Problem description:问题描述:
The collection "Professions" contains all professions available in the app.集合“专业”包含应用程序中可用的所有专业。 In this form the user should be able to select certain professions individualy (for a profession filter).在这种形式中,用户应该能够 select 某些行业个性化(用于行业过滤器)。 Every selected profession is contained in the collection "SelectedProfessions".每个选定的职业都包含在“SelectedProfessions”集合中。 The problem is that I can't bind (or render) the checkboxes value according to the helper property "CheckIfProfessionIsAssigned", which determines if this profession is currently selected by the user.问题是我无法根据帮助属性“CheckIfProfessionIsAssigned”绑定(或渲染)复选框值,该属性确定用户当前是否选择了该职业。
Didn't try these myself, but based on this answer - https://stackoverflow.com/a/60343185 - something like this might work to initially check the checkboxes:我自己没有尝试过这些,但基于这个答案 - https://stackoverflow.com/a/60343185 - 这样的事情可能会在最初检查复选框时起作用:
<input type="checkbox" checked="@CheckIfProfessionIsAssigned(prof)">
You could alternatively try to create a dictionary of integers and booleans named professionsSelected
in which to store for each profession ID if it is selected or not, and then bind that to the checkboxes, like:您也可以尝试创建一个整数和布尔值字典,命名为professionsSelected
,如果每个职业 ID 被选中,则在其中存储它,然后将其绑定到复选框,例如:
<input type="checkbox" @bind="@professionsSelected[prof.Id]" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.