Search code examples
c#asp.net-coretwitter-bootstrap-3blazorblazor-server-side

Using Blazor checkbox switcher


Is this the way you would normally use a switcher? For example, in this case I'm disabling it by setting variable to "disabled".

How do you get the value if it's checked or not in the @code section?

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<div class="form-check form-switch">
  <input class="form-check-input" type="checkbox" id="mySwitch" name="darkmode" @isChecked>
  <label class="form-check-label" for="mySwitch">Dark Mode</label>
</div>

<label>@isChecked</label>
@code{
    string isChecked;

    protected override void OnInitialized()
    {
        isChecked = "disabled";
    }
}

Solution

  • You may try:

        <InputCheckbox @bind-Value="@selected" disabled="@disabled"> </InputCheckbox>
        <button onclick="@Switch">Disable/Enable Checkbox</button>
        @code {
            
            private  bool selected{ get; set; }
            
            private bool disabled { get; set; } = false;
    
           private void Switch()
           {
    
              disabled = !disabled;
           }
        }
    

    check selected field to know if checkbox is checked or not