Skip to content

CheckboxListGeneric 不会默认选中 bind-Value 值 #5867

Answered by ArgoZhang
gudufy asked this question in Q&A
Discussion options

You must be logged in to vote

@gudufy 看到你的代码了,跟我猜测的基本一致

private List<SelectedItem<SysRole>> RoleItems { get; set; } = new List<SelectedItem<SysRole>> 
{ 
    new SelectedItem<SysRole> { Text="Administrator", Value= new SysRole { Id = 1, Name = "Administrator" } }, 
    new SelectedItem<SysRole> { Text= "Editor", Value= new SysRole { Id = 2, Name = "Editor" } } 
};

你的数据源集合内部候选项都是 new 出来的。

<div class="col-12">
    <CheckboxListGeneric TValue="SysRole" @bind-Value="v.Roles" Items="RoleItems" />
</div>

双向绑定值 v.Roles 也是你在另外一个地方 new 出来的。这如何要勾选?他们并不相等。这就是问题所在

public class SysRole
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
}

增加 [Key] 即可

注意你的代码中 SysRole 是混乱的,同样的 Editor 集合中的 Id 是 2 数据中是 1

Replies: 4 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by ArgoZhang
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Question that needs to be answered
2 participants
Converted from issue

This discussion was converted from issue #5856 on April 24, 2025 00:38.