Reputation: 7851
I extracted my issue to the simple code, that just doesn't work as expected:
<input type="checkbox" checked=@Visible @onchange="args=> {Visible=true;}"/>
@code
{
public bool Visible { get; set; } = true;
}
For some reason I want the checkbox to stay checked even if I clicked it (unchecked it). I cannot figure that out even with StateHasChanged()
or InputCheckBox
element.
This may sound stupid thing to do, but as I said, it is extracted code from complex one, that makes sense. Disabling checkbox is not solution here.
Upvotes: 1
Views: 1649
Reputation: 30074
See Reset input field value if value is invalid in Blazor for detailed explanation in a very similar question I answered a little while ago.
Basically, the DOM held by the Renderer looks like this:
<input type="checkbox" checked ....>
When you unclick the check box the actual browser DOM is now out of sync with the Renderer DOM. The onchange
event gets fired and the new value is passed to the event in the ChangeEventArgs
. It's still checked in the Renderer DOM, though unchecked in the Browser DOM. You then set it to this for the next render:
<input type="checkbox" checked ....>
The Renderer DOM sees no difference, and therefore doesn't send an update to the Browser. The code below forces that change by setting the Browser DOM to the unchecked state before reverting to the correct state.
<div class="container">
<div class="col p-2 m-2">
<input type="checkbox" checked=@Visible @onchange="OnChangeCheck" />
</div>
<div class="col p-2 m-2">
<input type="checkbox" checked=@Visible @onchange="OnChangeCheck1" />
</div>
</div>
public bool Visible { get; set; } = true;
async Task OnChangeCheck(ChangeEventArgs e)
{
Visible = false;
await Task.Yield();
Visible = true;
}
async Task OnChangeCheck1(ChangeEventArgs e)
{
Visible = true;
}
Upvotes: 3
Reputation: 2800
It is simpler if you add another hidden field with the value you want binded to the field model. Then the checkbox can be disabled because you don't need the value.
Upvotes: 0