In this lesson, you will learn how to seamlessly bridge the gap between C# and JavaScript by passing complex .NET objects across the interop boundary using JSON serialization.
Bridging the Gap with JSON
When you need to send data from C# to JavaScript—such as a complex configuration object or a user profile—you cannot simply pass a memory pointer. Because Blazor runs within a sandbox, it must serialize your C# objects into a JSON string before sending them to the browser's JavaScript engine. Blazor handles this conversion automatically using the System.Text.Json serializer.
The Mechanics of Serialization
When you invoke a JavaScript function via IJSRuntime.InvokeVoidAsync (or InvokeAsync<T>), Blazor serializes the C# object into a JSON representation. On the JavaScript side, this arrives as a standard JavaScript object.
For example, consider a C# class representing a UI theme:
public class ThemeConfig {
public string PrimaryColor { get; set; }
public int BorderWidth { get; set; }
public bool IsDarkMode { get; set; }
}
// Inside your Blazor component
var config = new ThemeConfig { PrimaryColor = "#ff5733", BorderWidth = 2, IsDarkMode = true };
await JS.InvokeVoidAsync("applyTheme", config);
In your JavaScript file, the config parameter is automatically available as a plain object:
window.applyTheme = (config) => {
console.log(config.primaryColor); // Accessing properties directly
document.body.style.backgroundColor = config.isDarkMode ? '#333' : '#fff';
};
Important Considerations
- Case Sensitivity: By default,
System.Text.JsonusescamelCasefor property names when serializing. Ensure your JavaScript code expects this naming convention (e.g.,primaryColorinstead ofPrimaryColor). - Circular References: Avoid passing objects with circular references (e.g., Parent -> Child -> Parent), as the serializer will throw an exception.
- Data Volume: Since every call involves string serialization and parsing, keep the payload size manageable to ensure the interop bridge remains performant. If you are passing massive datasets, consider sending only the minimum required state or using a more efficient streaming approach.
Key Takeaway: Blazor automatically serializes C# objects into JSON, allowing you to pass structured data to JavaScript seamlessly—just ensure your property naming conventions match your JavaScript expectations.