Originally posted on 2022-11-17
I found myself needing to update an SVG tag dynamically in a BlazorWASM project today and I couldn’t find exactly what I needed in the normal channels. So I created this simple hack and I’m gifting it to the world.
Add this to the head of your index.html:
<script>
window.updateInnerHtml = (id, data) => {
document.getElementById(id).innerHTML = data;
};
</script>
Inject the IJSRuntime
to your Razor page at the top like this:
@inject IJSRuntime JsRuntime
Add an SVG tag to your Razor page like this:
<svg id="testsvg"></svg>
Then somehow you’ll want to generate your SVG data and render that to a string. Once you’ve done that you can do this to update it in your C# code in the Razor page:
await JsRuntime.InvokeVoidAsync("updateInnerHtml", "testsvg", data);