Skip to content

Fix NullReferenceException when InputSelect (multiple) has no selection - #66868

Open
irfanajaffer wants to merge 64 commits into
dotnet:mainfrom
irfanajaffer:1028792_InputSelect
Open

irfanajaffer wants to merge 64 commits into
dotnet:mainfrom
irfanajaffer:1028792_InputSelect

Conversation

@irfanajaffer

@irfanajaffer irfanajaffer commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Description:

When data-binding to an array type in a Blazor component (for example using @Bind with a property of type T[]), formatting a null array value could throw a NullReferenceException. The exception occurred because the FormatArrayValue delegate inside BindConverter.MakeArrayFormatter() accessed the array's Length (value.Length) without first checking whether value was null.
This change adds a null-guard at the start of the FormatArrayValue local function in BindConverter.cs:
if (value is null) return null;
This short-circuits formatting for uninitialized arrays and prevents the NullReferenceException when resolving the string representation during component parameter binding.

Root Cause

The local FormatArrayValue function assumed the incoming array was non-null and immediately accessed value.Length and iterated the elements. When a bound array property was null, this access caused a NullReferenceException. A simple null-check was missing at the start of the formatter.

Testing

Added a unit test that exercises the array formatter with a null array input and asserts that:
No exception is thrown when formatting a null array.
The formatter returns null (or the expected string representation for null per contract).
Verified existing binding tests still pass.

Fixes #54431

@irfanajaffer
irfanajaffer requested a review from a team as a code owner May 27, 2026 10:29
@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label May 27, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label May 27, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

@irfanajaffer

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree company="Syncfusion, Inc."

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

When this feature landed, #33950, E2E tests were added. Let's patch their coverage in this PR with a null array test -> next to

<InputSelect @bind-Value="person.TicketClass" size="4" multiple>

Beyond that, I'm thinking if null is really better than "[]". Is there a specific case when differentiation between never-selected from all-unseleced matters?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

@irfanajaffer irfanajaffer reopened this Nov 5, 2026
@PureWeen

Copy link
Copy Markdown
Member

/review

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

A duplicate test declaration prevents compilation, the null-formatting guard regresses scalar and custom-converter behavior, and missing-array handling conflicts with the expected null contract and new test assertions.

3 open issues
1 resolved since last review

Review effort: Balanced

@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 f779fe0a164810986df7333302f78a7e556defa3 found one verified build blocker and surfaced two verifier-gated unresolved candidates inline.

  • Verified: duplicate FormatValue_Array_Null() methods prevent the Components test project from compiling.
  • Unresolved: whether the public generic null short-circuit changes custom TypeConverter output depends on target-version BCL dispatch evidence not present in the bundle.
  • Unresolved: whether the new int[] no-elements assertion reaches the empty-array branch depends on the assigned FormDataReader path or immutable validation evidence.

Existing feedback already covers the separate missing-array semantic concern at discussion 4466972422: omitted arrays becoming empty can affect required validation and null-based application defaults. Deduplication is neutral and does not endorse or resolve that thread.

Both routed guides completed their in-scope source checks using gpt-5.6-sol: docs/CrossCuttingGuidance.md and docs/BlazorComponentsGuidance.md. Security assessment and execution of builds, tests, CI, browsers, samples, trimming, or runtime behavior were excluded. Material changes were covered by the routed guides; no additional specialist guide covered FormMapping as a standalone domain.

Provenance: version-2 frozen bundle; head f779fe0a164810986df7333302f78a7e556defa3; merge base 1c94b15aa54d3d490d0ee060b7d496db3cb291e7; base tip and immutable guidance source 2bf69e1acc6a6418b4278b90873665891752cc16. This is source-only proof, not runtime validation. Frozen feedback only was observable; feedback posted after bundle preparation was not checked.

Generated by ASP.NET Core Pull Request Review for #66868 · copilot · gpt56 · 336.8 AIC · ⌖ 8.54 AIC · ⊞ 20.1K
Comment /review to run again

@PureWeen

Copy link
Copy Markdown
Member

The local G/S/O panel completed at f779fe0a164810986df7333302f78a7e556defa3. Existing agent feedback still needs attention: the duplicate test declaration and nullable-temporal formatting change are source-supported. No duplicate inline comments were added.

Informational only

Each item below is non-blocking: 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 — null reset followed by an option update: At BindConverter.cs:688, a null array removes the value attribute rather than producing "[]". The S/O arms traced a possible deferred-selection failure when a previously non-null model becomes null and an option is later inserted. The required contract for that sequence was not established, and the O arm found that its newer base-tip JavaScript already tolerates the removed value. This is not a verified new regression.
  • Unresolved — absent-array allocation: At CollectionConverter.cs:256, the empty-array fallback rents/returns a buffer and creates an empty array. No benchmark or binding performance contract established material harm.
  • Discarded checks: The arms did not establish a pooled-buffer leak, phantom nested elements, altered C# required-member presence checks, dictionary materialization, a public API addition, missing Selenium coverage, swallowed renderer exceptions, or a browser-wait defect. Recursive expected-leaf edits were not asserted; non-null empty arrays already formatted successfully; jagged inner-null handling improves the old path. Test-asset/name-collision and dispatcher checks did not establish a defect. The hypothesis that the public null-array path formats as "[]" was contradicted by the generic early return. These are routine discarded checks, not requests for changes.

Untested coverage gaps, separate from those discarded checks: The arms identified no dedicated test for non-null -> null followed by option insertion, or for the Minimal API [FromForm] effect of the missing-array change. The ordinary deselect-all unit/E2E scenarios would not by themselves guard the original null-formatting failure; the null-initial and static-SSR scenarios target that boundary. FormMapping was inspected through the two routed guides, without a standalone specialist guide.

The mapper assertion and custom-TypeConverter uncertainties are already posted here and here, so they are not repeated.

Validation boundary: all three arms used frozen source only; no local product build, test, or browser execution was performed.

Human-directed and GitHub Copilot-generated.

@irfanajaffer

Copy link
Copy Markdown
Contributor Author

Hi @PureWeen ,

Thanks for the review. I've addressed the reviewer concerns that were identified as source-supported:

  • The duplicate FormatValue_Array_Null() declaration has been removed, eliminating the CS0111 compilation issue while preserving the intended coverage through uniquely named tests.
  • The generic null handling was narrowed to array types only. Non-array types continue to flow through the existing formatter dispatch path, preserving nullable temporal formatting and custom TypeConverter behavior. Additional regression tests were added to verify these scenarios.
  • The omitted-array behavior was restored to the existing contract. Missing array form data now returns default rather than materializing an empty array, and the corresponding mapper and SSR tests were aligned with the restored null semantics.

Regarding the informational notes:

  • The null-to-option-insertion sequence was not part of the reported issue and no regression was established during review.
  • The empty-array fallback in CollectionConverter has been removed as part of restoring omitted-array semantics, so missing array data no longer allocates and returns an empty collection.
  • The discarded checks do not appear to represent actionable defects tied to this issue.

The intent of the final patch is to keep the fix narrowly scoped to the InputSelect multiple-selection null scenario while preserving existing formatting and form-mapping behavior.

anefiox added a commit to anefiox/pr-buddy that referenced this pull request Nov 17, 2026
Each rule covers a defect a human reviewer found on a real open PR
that PR Buddy missed:

- PRB018: a load guard is set inside a try before later work that can
  fail, so the early return blocks every retry (LykosAI/StabilityMatrix#1795)
- PRB019: a new collection field of objects that only grows, or is only
  cleared in another method (dotnet/winforms#13953)
- PRB020: a [Flags] enum member whose value isn't a single bit
  (DapperLib/Dapper#1590)
- PRB105: a test looks up a non-public member through reflection
  (dotnet/aspnetcore#66868)

None of them fires on the other compared PRs. PRB019 skips memo caches
that are read in the same method that adds to them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PureWeen
PureWeen requested a balanced review from Copilot November 17, 2026 21:47
@PureWeen

Copy link
Copy Markdown
Member

/review

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.

🟢 Approval recommended

No active review issues are recorded for the null-array formatting change.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

@PureWeen

Copy link
Copy Markdown
Member

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

The GPT-5.6 Sol, GPT-6.1 Sol, and Opus 5.5 arms completed their reviews of 6afc2d64bf7e1e3e6b6b5f554e29ee85489580ed. Earlier agent findings are resolved or outdated; no duplicate inline comments or approval review are being submitted.

Informational notes, not change requests

  • Unresolved process metadata: frozen source cannot establish human API/process acknowledgement for the changed null-array behavior of BindConverter.FormatValue<T> (BindConverter.cs:688). No public signature break or source defect was identified.
  • Discarded routine checks: no new regression was established for scalar/custom formatter dispatch, omitted-array mapping, DOM selection after null, inner jagged-array nulls, renderer exception propagation, annotation-only changes, or the internal setter. Recursive expected-fixture edits, XML documentation, the short-circuited IsArray check, test layout, and formatting did not establish a material defect. The previously reported duplicate declaration, overly broad null guard, and omitted-array fallback are repaired at this head.

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.

No concrete provisional finding required a candidate-verifier invocation.

Untested coverage boundaries, separate from discarded checks: direct setter calls and ordinary empty-array deselection are not independent proof of the null-array fix. No dedicated new populated-to-null-then-option-insertion test was identified; source consumer guards were assessed instead. FormMapping was covered by the two routed guides, not a standalone specialist.

Validation boundary: all three arms assessed frozen source and test coverage; no local product build, test, or browser execution was performed.

Human-directed and GitHub Copilot-generated.

@kotlarmilos

Copy link
Copy Markdown
Member

@ilonatommy, the current head adds an SSR E2E test for the reported scenario. It deselects all options for a [SupplyParameterFromForm] array and verifies the value is null after the POST and re-render. Could you take another look and update your review?

@kotlarmilos

Copy link
Copy Markdown
Member

Could we keep this focused on the null-array rendering failure? The CollectionConverter and DictionaryConverter changes also affect how missing nested collections are mapped. Can we avoid that behavior change or handle it separately?

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-approved 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 with multiple enabled throws NullRefException if nothing is selected

5 participants