Pre-selected values of multi dropdown based on object list

I have a dropdown configured like this:

            <RadzenDropDown Data="roles"
                            TValue="List<Role>"
                            @bind-Value="user.Roles"
                            TextProperty="Description"
                            Multiple="true"
                            AllowClear="true"
                            AllowSelectAll="false"/>

The user and role class:

public class User
{
   public int UserId {get; set;}
  
   public List<Role> Roles {get; set;}
}

public class Role 
{
    public int RoleId {get; set;}

    public string Description {get; set;}
}

The Data and bind-Value properties are both initialized after making a call to the backend API.

The problem is that when the dropdown is created, if the user object already has a list containing roles, the dropdown will show the amount of roles selected, but the checkboxes will not be checked.

Can the dropdown pre-check based off of a list of objects?

image

In the screenshot above, the user.Roles list has 2 items: Administrator and Carousel Manager. How can I make the items be checked in the list by default?

The objects in user.Roles might have different HashCode compared to the objects in roles. Try to set ValueProperty to RoleId and use just the ids for @bind-Value.

I ran into the exact same issue (with users and roles also)! The user.roles is an entity framework model, so it would be nice if the component took care of adding and removing. If I use a list of ids, I would have to keep track of what was added and removed, which kind of defeats the purpose of using EF.

I just found a solution. If you override the Equals and GetHashCode methods in the Role class to compare by id instead of by reference, it works!

Here's what I have:


public class Role
{
    public int Id { get; set; }
    [Required]
    [MaxLength(100)]
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }

    public override bool Equals(object obj) => obj is Role role && Id == role.Id;

    public override int GetHashCode() => Id.GetHashCode();
}

I'm still learning C# myself, but I believe you could also just change the Role class to a record. Records are compared by value instead of reference by default.