Skip to content

Fix InputSelect initial selection for null values - #70343

Open
VigneshwaranGovindharajan wants to merge 2 commits into
dotnet:mainfrom
VigneshwaranGovindharajan:41222-inputselect-null-selection
Open

VigneshwaranGovindharajan wants to merge 2 commits into
dotnet:mainfrom
VigneshwaranGovindharajan:41222-inputselect-null-selection

Conversation

@VigneshwaranGovindharajan

@VigneshwaranGovindharajan VigneshwaranGovindharajan commented Nov 6, 2026 •

Copy link
Copy Markdown

Description

An InputSelect bound to an initially null property could display its first option while the bound model remained null. Submitting the form without changing the selection therefore retained null despite displaying a non-null option.

This change:

  • Emits an empty-string value when the formatted single-select value is null.
  • Leaves no option selected when no empty-valued option exists.
  • Selects an existing empty-valued option when present, including when it is not the first option.
  • Preserves the null model value until user interaction changes it.
  • Leaves parsing, validation, event binding, and the multiple-select branch unchanged.
  • Adds browser regression coverage for strings, nullable integers, nullable enums, submission, selection, and reset behavior.

This intentionally corrects the initial interactive display. Applications relying on the previous first-option display for null values will observe a behavioral change. No public API signatures are added or changed.

Root Cause

The single-select rendering path passed CurrentValueAsString directly to RenderTreeBuilder.AddAttribute.

When that value was null, the builder omitted the element’s attribute frame. No initial value assignment reached the browser, allowing its default first-option selection.

The fix explicitly emits an empty string:

- builder.AddAttribute(8, "value", CurrentValueAsString);
+ builder.AddAttribute(8, "value", CurrentValueAsString ?? string.Empty);

This follows the DOM renderer’s existing null-as-empty-string convention without changing the bound model or parsing behavior.

Testing

Added browser regression coverage in FormsTest:

  • InputSelectWithInitialNullValueSelectsEmptyValue
    • Initially null string without an empty-valued option.
    • Initially null nullable integer.
    • Initially null string with an empty-valued option positioned second.
    • Unchanged model values and selection after untouched submission.
  • InputSelectWithNullValuesPreservesBindingAndResetBehavior
    • User selection and model updates.
    • Existing empty-string parsing behavior.
    • Form submission and programmatic reset to null.
  • InputSelectWithNullableEnumPreservesSelectionAndReset
    • Initially null nullable enum.
    • User selection and programmatic reset.

Each initial-null regression case was confirmed to fail at the expected selection assertion without the fix and pass with it in both Server and WebAssembly execution. The binding/reset preservation test passed with and without the fix.

Forms browser tests - Server and WebAssembly

dotnet test .\src\Components\test\E2ETest\Microsoft.AspNetCore.Components.E2ETests.csproj --no-restore -p:UseIisNativeAssets=false --filter "FullyQualifiedName~Microsoft.AspNetCore.Components.E2ETest.Tests.FormsTest.|FullyQualifiedName~Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests.ServerFormsTest." --logger "console;verbosity=normal" -v:q
image

Result: 100 passed, 0 failed, 0 skipped.

Forms component unit tests

dotnet test .\src\Components\Web\test\Microsoft.AspNetCore.Components.Web.Tests.csproj --no-restore -p:UseIisNativeAssets=false --filter "FullyQualifiedName~Microsoft.AspNetCore.Components.Forms." --logger "console;verbosity=minimal" -v:q
image

Result: 138 passed, 0 failed, 0 skipped.

Both sequential verification commands built successfully and exited with code 0. Initial parallel attempts encountered shared build-output file locks; sequential retries completed successfully.

Manual Validation

Used an in-tree Blazor sample with Microsoft Edge 156.0.4314.58 on Windows.

  • Reproduced the initial selection/model mismatch consistently across 10 runs without the fix.
  • Confirmed corrected selection and unchanged null model values across 10 runs with the fix.
  • Verified ordinary selection, empty-string placeholder selection, untouched submission, and programmatic reset.
  • Verified Interactive Server behavior without prerendering and after interactive activation with prerendering enabled.
  • Removed the temporary sample after permanent browser coverage passed.

Scope and Related Work

  • The investigated delayed-options scenarios showed the same selection mismatches with and without the fix. Those pre-existing limitations are not addressed here.
  • Related PR Fix InputSelect not handling null for nullable bool #65222 addresses nullable-Boolean formatting. This change does not modify that formatting behavior.

Fixes #41222

@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label Nov 6, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @VigneshwaranGovindharajan. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

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.

🔵 Needs a closer look

The required frozen source-and-guidance bundle was not supplied, leaving revision-bound checks and independent reviewer gates incomplete.

No open issues 🎉

What changed in this PR

Fixes #41222 by aligning the initial interactive display of a single-value InputSelect with its null-bound model, rather than displaying the browser’s default first option.

Changes:

  • Emits an empty-string value for null selections, selecting an empty-valued option when present or leaving no option selected otherwise.
  • Preserves parsing, binding, validation, and multiple-select behavior.
  • Adds browser regression coverage for null strings, nullable integers, nullable enums, submission, selection, and reset behavior.
File Description
src/​Components/​Web/​src/​Forms/​InputSelect.cs Emits an empty string when the formatted single-select value is null.
src/​Components/​test/​testassets/​BasicTestApp/​Index.razor Registers the null-selection test component.
src/​Components/​test/​testassets/​BasicTestApp/​FormsTest/​InputSelectNullValueComponent.razor Provides null-bound selections and submission/reset controls for testing.
src/​Components/​test/​E2ETest/​Tests/​FormsTest.cs Adds browser assertions for initial selection, model preservation, binding, and resets.

Review effort: Balanced

@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.

Reviewed commit d36fc4cbd8b415271d1d6e349e6c5f84d179128f (Round 1). One behavioral question/edge case is noted inline on InputSelect.cs regarding <option selected disabled> placeholders that do not specify value="".

else
{
builder.AddAttribute(8, "value", CurrentValueAsString);
builder.AddAttribute(8, "value", CurrentValueAsString ?? string.Empty);

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.

Emitting value="" unconditionally when CurrentValueAsString is null changes initial interactive rendering when the author provides an explicit <option selected disabled>Choose…</option> placeholder without a value="" attribute (where the option's DOM .value defaults to its text content):

<InputSelect @bind-Value="model.Country">
    <option selected disabled>Choose…</option>
    <option value="US">US</option>
</InputSelect>

Previously, RenderTreeBuilder.AddAttribute(8, "value", (string?)null) omitted the value attribute frame on initial render, so _blazorDeferredValue was not set and the browser honored the selected attribute on <option selected disabled>Choose…</option> (selectedIndex == 0). With CurrentValueAsString ?? string.Empty, Blazor records _blazorDeferredValue = '' (DomSpecialPropertyUtil.ts:84) and applies select.value = '' after child options are inserted (BrowserRenderer.ts:303), which matches no option and resets selectedIndex to -1 (a blank <select>).

Is blanking an author-marked <option selected> without value="" on initial render intended, or should applyAnyDeferredValue / InputSelect preserve an explicit selected option when value is "" and no option has value=""? Either way, please add a test row covering <option selected disabled>Choose…</option> (without value="") when bound to null.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for highlighting this case. I added browser coverage for both:

  • <option selected disabled>Choose…</option>
  • <option selected disabled value="">Choose…</option>

I confirmed your observation in both Server and WebAssembly:

Initially null model Before the fix With the fix
Selected placeholder without a value attribute Placeholder selected (selectedIndex = 0) No selection (selectedIndex = -1)
Selected placeholder with value="" Placeholder selected (selectedIndex = 0) Placeholder selected (selectedIndex = 0)

The tests also verify selecting US updates the model and resetting it to null restores the respective selection behavior.

Without the fix, the two no-value cases fail at the initial-selection assertion; the explicit-empty-value controls pass. After restoring the fix, all four cases pass.

No additional production-code changes were made. The tests currently document the proposed behavior: the bound null value, represented as an empty string, overrides an explicitly selected option whose effective value is its nonempty text.

Could you confirm whether this override is intended, or whether the explicitly selected placeholder should be preserved? I have not changed the renderer to preserve it pending that decision.

@PureWeen

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 e86b5e3f868e574aa8287057750fa6f6d452fbc4.

One P2 candidate is published inline as unresolved: frozen source proves that static rendering preserves an explicit selected placeholder while the interactive path reapplies an empty select value, but the resulting browser selection transition requires an unavailable target-version DOM contract or immutable browser validation artifact.

Existing feedback coverage: inline thread 4555336213 and reply 4560077095 already discuss the related interactive behavior for an explicitly selected placeholder without value="". This is recorded for deduplication only, not as endorsement or resolution; the static-SSR-to-activation consequence was independently assessed.

Guide completion: docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md completed with gpt-5.6-sol workers (reasoning effort: not supplied/runtime default). Runtime execution, builds, CI, browser workflows, and samples were excluded by the source-only boundary; security assessment was excluded by assigned policy. No materially changed area was left uncovered.

Provenance and boundary: evidence came only from the ready version-2 frozen bundle for PR 70343, merge base e644b0c25f8862a067c2fb132182aacf8d671837, base tip and trusted guidance commit 59835e6087e90b972a905dc303523cfbb5d828ef. No target code or tests were executed. Feedback is frozen at bundle preparation; later feedback is not observable.

Limitations: tracked Git bytes only; symlink, submodule, and LFS targets are inert. Browser DOM behavior needed to settle the inline candidate is outside the frozen source proof.

Generated by ASP.NET Core Pull Request Review for #70343 · copilot · gpt56 · 203.5 AIC · ⌖ 12.5 AIC · ⊞ 18.8K
Comment /review to run again

else
{
builder.AddAttribute(8, "value", CurrentValueAsString);
builder.AddAttribute(8, "value", CurrentValueAsString ?? string.Empty);

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.

[P2] [UNRESOLVED] Static SSR may retain this placeholder while interactive activation clears it

When a null-bound InputSelect contains <option selected disabled>Choose...</option> without value="", this line gives the interactive renderer an explicit empty value. The static renderer preserves the option's explicit selected attribute, while the interactive path reapplies select.value = "" after inserting options.

Why unresolved: The frozen repository does not include a target-version browser/DOM contract, browser implementation source, or immutable validation artifact proving both that static HTML parsing preserves the valueless selected option and that assigning HTMLSelectElement.value = "" with no empty-valued option clears selection.

Minimal repro: prerender that null-bound select, observe the placeholder, then activate it interactively and check whether selectedIndex changes from 0 to -1.

If that transition is confirmed, make static and interactive rendering treat the explicit select value consistently and add prerender-to-activation coverage.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks. The existing tests cover interactive rendering, not the prerender-to-activation transition. I will investigate that transition separately; no further production changes have been made pending clarification of the intended placeholder behavior.

@PureWeen

Copy link
Copy Markdown
Member

Round 2 reviewed e86b5e3f868e574aa8287057750fa6f6d452fbc4. The three local review arms found no new verified defects or intent questions.

The new tests cover the cases requested in the earlier placeholder thread. The behavior decision remains open in the author reply. That prior question keeps agent-reviewed-needs-changes in place, not the informational items below.

The following note applies to each item:

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.

  • [UNRESOLVED] Late empty option after user selection. Start with a null-bound string select containing keyed options A and B. Select B, wait for the model to show B, then append an empty-valued option. One arm traced a stale deferred empty value that could select the new option while the model remains B. The verifier required browser evidence for that complete sequence. This is not a verified regression.
  • [DISCARDED] Static SSR without an empty option. One arm considered a null-bound select containing only nonempty options. It discarded this incomplete-fix claim because the old and new static markup match for that input. It found no binding contract that requires a different result.
  • [DISCARDED] Options arrive while the model remains null. One arm considered options inserted in a later render batch, without an intervening user selection. It found no harmful old-versus-new difference for nonempty options. Selecting a later empty-valued option follows the null-to-empty convention. This differs from the first item's accepted-user-selection sequence.

The existing SSR-to-activation diagnostic already covers the placeholder transition, so this comment does not repeat it.

These reviews used frozen source. They did not run browser validation.

Human-directed and GitHub Copilot-generated.

@VigneshwaranGovindharajan

Copy link
Copy Markdown
Author

@PureWeen , Thanks for the follow-up. I understand that the new tests satisfy the requested placeholder coverage, while the intended behavior for an explicitly selected placeholder without value="" remains undecided.

The existing tests cover interactive Server and WebAssembly rendering; they do not verify the prerender-to-interactive transition. I will investigate that transition separately before proposing any further production changes.

Could you confirm the intended behavior: should the null binding clear this explicitly selected placeholder, or should the placeholder be preserved?

I also noted the late-added empty-option scenario. Since it is currently unverified and informational, I will avoid expanding this fix without browser evidence of a regression.

@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 Nov 24, 2026

This branch was previously deployed

1 inactive (outdated) deployment
copilot-pat-pool — d36fc4cb Deployed Nov 6, 2026 by dotnet-policy-service[bot] via pat_pool #2210
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 community-contribution Indicates that the PR has been added by a community member 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.

Blazor InputSelect sets wrong selected Option

3 participants