Skip to content

Conversation

@rolandVi
Copy link
Contributor

Enable IJSObjectReference to handle null/undefined values

Problem

Currently, calling DotNet.createJSObjectReference(null) or DotNet.createJSObjectReference(undefined) throws an error: This forces developers to write workaround code when JavaScript functions might return null/undefined values.

Solution

Modified createJSObjectReference to handle null/undefined values by returning a special sentinel object with __jsObjectId: -1 instead of throwing an error. The .NET side JSON converter recognizes this sentinel value and returns null for the IJSObjectReference?.

Changes

  • JavaScript side: createJSObjectReference() now accepts null/undefined and returns {__jsObjectId: -1}
  • .NET side: JSObjectReferenceJsonConverter recognizes the -1 sentinel and returns null
  • Disposal: Updated disposeJSObjectReference() to safely handle null references (skip disposal for id -1)

Benefits

  • Non-breaking change: Converts from exception to success

Fixes #52070

@rolandVi rolandVi requested a review from a team as a code owner July 10, 2025 14:27
@github-actions github-actions bot added the area-blazor Includes: Blazor, Razor Components label Jul 10, 2025
@dotnet-policy-service dotnet-policy-service bot added the community-contribution Indicates that the PR has been added by a community member label Jul 10, 2025
@oroztocil
Copy link
Member

oroztocil commented Jul 10, 2025

Please check that you get an expected result when you do var result = await JS.GetValueAsync<IJSObjectReference>("someProp"); in both cases:

  • When someProp is defined in the scope with value set to null or undefined.
  • When someProp is not defined in the scope.

@ilonatommy ilonatommy added this to the 10.0-preview7 milestone Jul 14, 2025
Copy link
Member

@oroztocil oroztocil left a comment

Choose a reason for hiding this comment

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

Nice! 🚀

@ilonatommy ilonatommy merged commit 36e93fa into dotnet:main Jul 14, 2025
28 checks passed
@ilonatommy ilonatommy removed the community-contribution Indicates that the PR has been added by a community member label Jul 15, 2025
@rolandVi rolandVi deleted the jsobjectreference-handle-null branch August 14, 2025 15:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow JS.InvokeAsync<IJSObjectReference> calls to return null/undefined

4 participants