A demonstration project showcasing how to call JavaScript functions from .NET code in a Blazor Server application.
This project demonstrates the complete setup and usage of JavaScript interoperability (JS Interop) in Blazor Server. It includes a working example that calls a custom JavaScript modal dialog from a Razor component.
- Interactive Server Rendering: Components with
@rendermode InteractiveServerfor client-side interactivity - JS Interop: Calling JavaScript functions from .NET using
IJSRuntime - Custom Modal Dialog: A styled modal component triggered from Blazor
BlazorServerInteropDemo/
├── Program.cs # Service configuration
├── Components/
│ ├── App.razor # Root component with JS script reference
│ ├── Layout/ # Layout components
│ └── Pages/
│ └── Alert.razor # Example component using JS Interop
└── wwwroot/
└── scripts.js # Custom JavaScript functions
Enable interactive server components:
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();Include the custom JavaScript file in the HTML head:
<script src="@Assets["scripts.js"]"></script>Enable interactive server rendering and inject IJSRuntime:
@page "/alert"
@rendermode InteractiveServer
@inject IJSRuntime JSUse JS.InvokeVoidAsync() to call JavaScript functions:
@code {
public async Task ButtonClicked() =>
await JS.InvokeVoidAsync("showColoredModal", "Calling JavaScript from .NET!", "#007bff");
}Define JavaScript functions that can be called from .NET:
function showColoredModal(message, hexColor) {
const modal = document.createElement("div");
// ... modal creation logic
document.body.appendChild(modal);
}dotnet runNavigate to /alert to see the JS Interop demo in action.
| Concept | Purpose |
|---|---|
@rendermode InteractiveServer |
Enables interactive rendering on the server |
@inject IJSRuntime JS |
Injects the JavaScript runtime into the component |
JS.InvokeVoidAsync() |
Calls a JavaScript function without return value |
wwwroot/scripts.js |
Custom JavaScript functions accessible from .NET |
- JS Interop only works with components marked as
@rendermode InteractiveServer - Place custom JavaScript files in the
wwwrootfolder - Import them in
App.razorafter the Blazor framework script - Use
InvokeAsync<T>()if the JavaScript function returns a value - Use
InvokeVoidAsync()for functions with no return value