TLDR; It is like the string/textbox binding works just fine on input controls, but the checkbox binding backed by Boolean properties does not work. I know the binding for checkbox values needs to used a 'checked' attribute instead of a 'value' attribute, but Blazor is supposed to handle that across different control types.
I'm doing some Blazor work (server-side app) with RC1 and cannot seem to get Boolean values binding to an input checkbox control. I believe that the syntax being used is correct (see below). As a simple test, I created a new project and simply replaced the index.razor page with the sample code below. When you run it, notice:
@page "/"
<div class="form-group">
<label for="last-name">Textbox Binding Test</label>
<input @bind="TestString" type="text" class="form-control" id="last-name" placeholder="Enter Last Name" />
</div>
<div class="form-group">
<label for="send-email-updates">Checkbox Binding Test</label>
<input type="checkbox" bind="@TestBool" id="send-email-updates" />
</div>
@code {
private bool _testBool = true;
protected bool TestBool
{
get { return _testBool; }
set
{
_testBool = value;
System.Diagnostics.Debug.WriteLine($"Value of {nameof(TestBool)} = {value}");
}
}
private string _testString = "Test Value";
protected string TestString
{
get { return _testString; }
set
{
_testString = value;
System.Diagnostics.Debug.WriteLine($"Value of {nameof(TestString)} = {value}");
}
}
}
This behavior was observed regardless of making the properties public, used auto-properties (no private variables), or removed the control name/id attribute values. This seems to happen regardless of whether I use the @code directive on the page or separate out a viewmodel that inherits from ComponentBase.
The bottom line is that I'm able to get text-based values when a user submits the form, but all the Boolean properties seem to remain as they were when first initialized.
When you look at both controls:
<input @bind="TestString" type="text" class="form-control" id="last-name" placeholder="Enter Last Name" />
<input bind="@TestBool" type="checkbox" id="send-email-updates" />
It is clear you are mixing bind
and @bind
notations, probably from older Blazor editions.
This one works in rc1:
<input type="checkbox" @bind="TestBool" id="send-email-updates" />
but in general I would argue for using the <EditForm>
and related tags:
<EditForm Model="this">
<InputCheckbox @bind-Value="TestBool" />
</EditForm>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With