Skip to content

Fix checkbox binding when input type is set dynamically - #67716

Open
vendasankarsf3945 wants to merge 12 commits into
dotnet:mainfrom
vendasankarsf3945:fix-dynamic-input-type
Open

vendasankarsf3945 wants to merge 12 commits into
dotnet:mainfrom
vendasankarsf3945:fix-dynamic-input-type

Conversation

@vendasankarsf3945

@vendasankarsf3945 vendasankarsf3945 commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Checkbox not checked when input type is set dynamically

Description

This PR fixes a bug in Blazor's two-way binding where an <input> element with a dynamic type attribute (e.g. type="@InputType") does not render the correct initial state for bool bindings. When @InputType resolves to "checkbox" at runtime, the checkbox stayed unchecked even when the bound value was true.

Changes

Before

The first checkbox (with type="@InputType") is unchecked even though the bound value is true. The second checkbox (with type="checkbox" literal) is checked correctly. Both should be checked.

The cause: the Razor compiler cannot match a dynamic type against the checkbox-specific binding rule, so it falls back to a generic value-based binding. For a bool, the framework serializes true as an empty string. The runtime applies value to the input, but for a checkbox the value attribute is only the form-post value — it does not drive the visible checked state. Nothing sets .checked, so the checkbox renders unchecked.

Screenshot 2026-07-03 183405

After

Both checkboxes are checked on first render. The runtime now recognizes the wire format for a bool value ("" = true, null = false) and, when the input resolves to a checkbox at runtime, also sets the .checked IDL property. The same translation also fires when the type attribute changes at runtime, so the bound state is preserved across type transitions.

Screenshot 2026-07-09 161506

Fixes #44130

@PureWeen

PureWeen commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

I validated this change at 15c80667891d5131f8590ec6f8af132ea73f49f4 through the real Components E2E browser paths using the same assertions across the merge base, this PR head, and a textarea-only proof correction.

Server renderer (BASE / HEAD / CANDIDATE):

  • Dynamic checkbox, including a text-to-checkbox transition: FAIL / PASS / PASS.
  • Populated textarea value "Hello": PASS / FAIL ("") / PASS.
  • Shipped InputCheckbox checked state plus native submitted value "True": PASS / FAIL (checked=False; submitted=on) / FAIL (same).

The intended dynamic-checkbox fix works on this path, but the current implementation introduces two server-renderer regressions. Please preserve textarea deferred replay and distinguish generic Boolean wire values from an InputCheckbox form value. The textarea-only proof correction is not a complete fix.

I also repaired the canonical WebAssembly test harness and completed the same comparison there. WebAssembly BASE / HEAD / CANDIDATE is PASS / PASS / PASS for textarea and dynamic checkbox, and FAIL / FAIL / FAIL for InputCheckbox (checked=False; submitted=). Because that WebAssembly InputCheckbox assertion already fails at the merge base, it is not PR-specific evidence and should be investigated separately. The completed client run narrows, rather than invalidates, the two exact server regressions above.

I recommend revising this implementation. Before merge, a complete correction should pass all three server assertions and preserve the two green WebAssembly cases.

Written with the help of GitHub Copilot.

Copilot AI lite review requested due to automatic review settings August 25, 2026 12:57

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses a Blazor DOM update bug where @bind to a bool fails to reflect the initial checked state when an <input>’s type is provided dynamically (causing the binding to fall back to value instead of checked). It updates the DOM special-property application logic so checkbox state can be derived from Blazor’s wire-format for booleans even when type is applied/changes at runtime, and adds Jest coverage for the new behavior.

Changes:

  • Add special handling for dynamically setting <input type=...> so any previously-stashed deferred value can be replayed after the browser resets IDL state on type transitions.
  • Interpret Blazor’s wire-format boolean (""/null) for checkboxes by setting the .checked IDL property when appropriate.
  • Add a new Jest test suite validating checkbox behavior for dynamic type changes and deferred value replay.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/Components/Web.JS/src/Rendering/DomSpecialPropertyUtil.ts Adds type special handling and checkbox-specific boolean wire-format application via .checked.
src/Components/Web.JS/test/DomSpecialPropertyUtil.test.ts Adds unit tests covering dynamic type + deferred value replay + checkbox checked state behavior.
Suppressed comments (1)

src/Components/Web.JS/src/Rendering/DomSpecialPropertyUtil.ts:189

  • setDeferredElementValue now treats a checkbox value of '' as a boolean true and forces element.checked = true. This changes behavior for any checkbox whose value is intentionally set to an empty string (e.g. value="" or value="@someEmptyString"), because HTML checkbox value is a form-post value and should not drive the visual checked state.

If this behavior change is intentional, it would be good to document/justify it; otherwise, consider tightening the condition so only the bool-binding wire-format case triggers .checked updates (and add a regression test for value="" on a checkbox remaining unchecked unless checked is set).

  // Blazor wire-format encodes bool as '' (true) or null (false); any other string is a form-post value and must go to .value.
  if (element instanceof HTMLInputElement && element.type === 'checkbox' && (value === '' || value === null)) {
    element.checked = value === '';
    return;
  }

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@vendasankarsf3945

Copy link
Copy Markdown
Contributor Author

Hi @PureWeen,

Thank you for the detailed validation across all three server-renderer paths and for identifying the two regressions precisely.

Both regressions are addressed in the updated commit:

Textarea regression — The original implementation only handled HTMLInputElement inside setDeferredElementValue, dropping the fallback that writes .value for any other element. The fix restores a general typeof value === 'string' / value === null fallback at the end of setDeferredElementValue, which covers <textarea> (and any non-select, non-checkbox element).

InputCheckbox regression — The original fix translated any value on a checkbox to .checked, which forced checked = false when <InputCheckbox> applied its form-post value="True" frame. The fix distinguishes the two cases by only applying the .checked translation for exact Blazor wire-format bool values ('' = true, null = false). Any other string falls through to .value, so the checked frame and the form-post value frame remain independent and do not interfere with each other.

The WebAssembly InputCheckbox failure (FAIL / FAIL / FAIL) noted in the review was already present at the merge base and is not introduced by this PR — noted separately for follow-up.

Updated server-renderer assertions against the new commit:

Scenario Base Previous HEAD Updated
Dynamic checkbox (incl. text→checkbox transition) FAIL PASS PASS
Populated textarea value "Hello" PASS FAIL PASS
InputCheckbox checked + form-post "True" PASS FAIL PASS

Unit tests covering all three scenarios (plus the explicit text→checkbox transition path) are in DomSpecialPropertyUtil.test.ts.

@Youssef1313 Youssef1313 added the area-blazor Includes: Blazor, Razor Components label Sep 2, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Sep 26, 2026
@PureWeen

PureWeen commented Oct 2, 2026

Copy link
Copy Markdown
Member

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Source-only review of frozen head 6cea93e0a2e30e076a6f68d3cc31df18e9f78242 found one new P2 issue: changing a valued input to type=file replays the nonempty deferred value and can raise InvalidStateError, aborting the render batch.

Both routed guides completed independently with general-purpose workers on gpt-5.6-sol: docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md. Execution of PR code, tests, CI, browser workflows, and samples was excluded by the source-only boundary; security assessment was also excluded by the supplied policy. No materially changed area lacked a routed specialist guide.

Existing-feedback coverage: the empty-string checkbox ambiguity at DomSpecialPropertyUtil.ts:191 is a true-positive duplicate already recorded in review 5019197421, so it was not reposted. One candidate remains unresolved: replaying _blazorDeferredValue after a later compatible input-type change may overwrite a user edit, but the frozen bundle does not contain the browser-contract evidence needed to establish the old observable effect for a specific compatible transition. The earlier textarea, InputCheckbox value="True", and null-type-removal concerns are corrected at this head.

Provenance: ready v2 frozen bundle; merge base bf676af7baa13fa4d06be384b4285d5406161219; base tip and trusted guidance commit 4449eb585c8c82b5cf0e6f5d88f7ba73cbcadf62. This is source-only proof, not runtime verification. Evidence is limited to tracked frozen Git bytes; symlink, submodule, LFS-target behavior, post-freeze feedback, and external browser behavior not represented in the bundle were not independently observed.

Generated by ASP.NET Core Pull Request Review for #67716 · copilot · gpt56 · 323.6 AIC · ⌖ 11.3 AIC · ⊞ 17.5K
Comment /review to run again

@kotlarmilos kotlarmilos left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please preserve checkbox value="" semantics and the current user-entered value when changing input types, as this change currently checks empty-valued checkboxes and can overwrite typed text with a stale cached value. Additionally, please consolidate testing, E2E changes should not be needed for such fix.

@vendasankarsf3945

Copy link
Copy Markdown
Contributor Author

Please preserve checkbox value="" semantics and the current user-entered value when changing input types, as this change currently checks empty-valued checkboxes and can overwrite typed text with a stale cached value. Additionally, please consolidate testing, E2E changes should not be needed for such fix.

Updated the patch to address the review concerns:

  • Handle Boolean checkbox bindings in RenderTreeBuilder.
  • Preserve literal value="", explicit checked values (including false), and existing attribute omission behavior.
  • Remove JavaScript value replay to avoid stale-value restoration.
  • Retain updated binding targets when reusing event handlers.
  • Consolidate regression tests and remove the added E2E coverage.

All tests, whitespace, and patch-applicability checks pass locally.

@PureWeen

Copy link
Copy Markdown
Member

/review

@PureWeen

Copy link
Copy Markdown
Member

Copilot's local review panel found no issues to raise at this commit.

@kotlarmilos

Copy link
Copy Markdown
Member

This change looks broader than necessary because it adds checkbox-specific tracking throughout RenderTreeBuilder. Please consider a narrower fix and add focused coverage for uppercase checkbox types and null bool? bindings, which can leave the checkbox out of sync with its bound value.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Approval is blocked by active correctness issues in case-insensitive VALUE handling and binder-type inference after attribute splatting, along with a minor test-double cleanup.

3 open issues
1 resolved since last review

Review effort: Lite

Comment on lines +912 to +914
var isBooleanValue = valueIndex >= 0
? buffer[valueIndex].AttributeValueIsBooleanField
: (flags & InputAttributeFlags.OmittedBooleanValue) != 0 || hasNullableBooleanBinding;
Comment on lines +897 to +899
case "value":
valueIndex = attributesEnd;
break;
Comment on lines +1061 to +1077
var receiver = Mock.Of<IHandleEvent>();
var callback = useAsyncBinder
? EventCallback.Factory.CreateBinder<bool?>(receiver, _ => Task.CompletedTask, value)
: EventCallback.Factory.CreateBinder<bool?>(receiver, _ => { }, value);
builder.OpenElement(0, "input");
builder.AddAttribute(1, "type", "CHECKBOX");
builder.AddAttribute(2, "value", BindConverter.FormatValue(value));
builder.AddAttribute(3, "onchange", callback);
builder.SetUpdatesAttributeName("value");
builder.CloseElement();

var eventFrame = Assert.Single(builder.GetFrames().AsEnumerable(),
frame => frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == "onchange");
Assert.IsType<EventCallback>(eventFrame.AttributeValue);
Assert.Equal("checked", eventFrame.AttributeEventUpdatesAttributeName);
}

@PureWeen

Copy link
Copy Markdown
Member

/review

@PureWeen PureWeen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The local panel found three blocking issues at 72cb6ab435fffaacbec9ed235676a08a203a30b1.

Informational unresolved checks

  • The uppercase CHECKBOX string-setter path remains unproven because the frozen evidence did not establish both browser reflection behavior and exact Razor lowering.
  • Adding value/checked after closing the root element may reach an empty-stack Peek, but the path is invalid hand-written builder usage and was not runtime-validated.

Posted for informational purposes so the author can confirm the verifier didn't discard or leave unresolved a real finding; this item does not block agent-reviewed-approved.

Untested coverage gaps: no arm executed product tests, browser workflows, or runtime repros.

Validation boundary: all three voting arms performed frozen-source review only.

Human-directed and GitHub Copilot-generated.

}

var isBooleanValue = valueIndex >= 0
? buffer[valueIndex].AttributeValueIsBooleanField

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SetAttributeValue only replaces AttributeValueField, so a frame first added with a Boolean retains AttributeValueIsBooleanField. Closing the checkbox trusts that stale marker and renames a later string value (and the event update target) to checked. Please update or invalidate the Boolean provenance when replacing the payload, and add focused coverage for Boolean-to-string replacement.

frame.AttributeValueIsBooleanField = false;
frame.SequenceField = sequence;
_entries.Append(frame);
if (frame.AttributeValueField is bool)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Server, the valueless AddAttribute overload stores BoxedTrue, but replaying that frame here reclassifies it as Boolean-binding provenance. CloseElement then renames value to checked; WebAssembly retains value because its payload is string.Empty. Please preserve valueless-versus-Boolean provenance when copying a RenderTreeFrame so replay is platform-consistent.

[Theory]
[InlineData(true, false, true)]
[InlineData(false, false, true)]
[InlineData(true, true, false)]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These hasBinding: false rows pass with the production fix reverted: they skip the binder and assert the pre-existing value behavior. The target-branch Components test guidance requires every row in a regression theory to fail without the fix and disallows multi-test control matrices. Please remove these false-green rows and consolidate any needed control to a single appropriate case.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-reviewed-needs-changes area-blazor Includes: Blazor, Razor Components pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Checkbox is not checked when the bound value is true and if the input type is set by code

6 participants