Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How do you use @bind-Value:get and @bind-Value:set in a MudCheckbox to bind the value to whether an item exists in a collection?

$
0
0

UPDATE: I decided to answer my own question since I figured it out. Turns out I had the working code all along, but other errors were confusing me, and I didn't realize I had stumbled on the working version.


I have a MudForm that has multiple checkboxes for selecting roles for a user. I'm trying to bind the Value (checked state) of each checkbox to whether or not a certain role exists in an IEnumerable inside my model.

Notice the @bind-Value:get and :set attributes on the checkboxes. I've tried so many variations of what to put in there.

<MudForm Model="@model" @ref="@form"><MudStack><MudText Typo="Typo.h6">Roles</MudText><MudCheckBox @bind-Value:get="?????"                     @bind-Value:set="?????"                     Label="Admin" /><MudCheckBox @bind-Value:get="?????"                     @bind-Value:set="?????"                     Label="User" /></MudStack></MudForm><MudText Typo="Typo.h6">Selected Roles</MudText><MudText>@(string.Join(", ", model.Roles.Select(role => role.Name)))</MudText>@code {    MudForm form;    EmployeeViewModel model = new EmployeeViewModel        {            Roles = new List<RoleViewModel>            {                new RoleViewModel { Name = "Admin" }            }        };    private void OnRoleCheckChanged(string roleName, bool isChecked){    var roleExists = model.Roles.Any(r => r.Name == roleName);    if (isChecked)    {        if (roleExists) return; // Role already exists, no need to add it again        model.Roles = model.Roles.Concat(new[] { new RoleViewModel { Name = roleName } }).ToList();    }    else    {        // Remove the role since it is unchecked        if (roleExists)        {            //rebuild the list without the role            model.Roles = model.Roles.Where(r => r.Name != roleName).ToList();        }    }}    public class EmployeeViewModel    {        public List<RoleViewModel> Roles { get; set; } = new List<RoleViewModel>();    }    public class RoleViewModel    {        public string Name { get; set; }    }    }

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>