Blazor WebAssembly:JSInvokable方法更新变量后如何实现页面绑定同步更新?
Hey there! Let's break down why your scroll position display isn't syncing with the value set by your JSInvokable method, and how to fix it using Blazor's built-in state management.
The Root Cause
Blazor components automatically re-render when state changes during standard lifecycle events (like button clicks or component initialization). But when JavaScript calls a [JSInvokable] method, it happens outside of Blazor's default state tracking system. Even though you're updating the scrollPosition variable, Blazor has no clue the state changed—so it never triggers a UI refresh.
The Fix: Explicitly Trigger a State Update
To get the UI to sync, you need to tell Blazor explicitly that the component's state has changed by calling StateHasChanged(). Since JS interop calls might run on a non-UI thread, wrap this call in InvokeAsync() to ensure it executes on the correct thread.
Here's your updated code:
<div>Current Scroll Position: @scrollPosition.ToString()</div> @code{ long scrollPosition = 0; [JSInvokable("OnScroll")] public async Task OnScroll(string index) { if (int.TryParse(index, out var topIndex)) { scrollPosition = topIndex; // Tell Blazor to re-render the UI with the new value await InvokeAsync(StateHasChanged); } } }
Key Details:
- Changed the method return type to
Taskto support theawaitkeyword (you could usevoidwithInvokeAsync(StateHasChanged).ConfigureAwait(false), butTaskis cleaner for async operations). - Added
await InvokeAsync(StateHasChanged)right after updatingscrollPosition—this is the magic line that forces Blazor to refresh the UI. - Added a success check for
int.TryParseto avoid accidentally settingscrollPositionto 0 if the input string is invalid.
Why This Works
InvokeAsync()marshals the state change call to Blazor's UI synchronization context, which is critical for Server-Side Blazor (and a safe practice for WASM too).StateHasChanged()signals Blazor to compare the current state with the previous state, updating any UI elements that depend on changed values—like your scroll position display.
This approach keeps everything synced using Blazor's binding system, just like you wanted, without needing to handle the UI update directly in JavaScript.
内容的提问来源于stack exchange,提问作者Rowie

