asp.net-coreblazorblazor-server-side.net-9.0

Blazor SectionOutlet and SectionContent doesn't re-render on navigation


I was trying to call a Javascript function in Blazor global server rendered app with .NET 9. The .js file that contains that function is loaded via SectionContent.

I found that if I load the app with the page that has that SectionContent in it (for example /AddProduct), everything works fine, even after some navigating and back to that page.

But if I load the web app from any other page that doesn't have that .js file (for example /Home or /Products), it doesn't load correctly (loading Quill Editor). After some debugging and testing, I found out that the SectionContent is not dynamic and just loads once and after full refresh or loading.

I mean if you don't load the /AddProduct page (that contains that SectionContent with .js files in it) or refresh that page after navigating, it doesn't load those .js files or html tags. Even if you load the /AddProduct page, then navigate to any other page, those .js files or html tags stay there! That's weird.

I tested the same (just testing) with HeadContent and that works perfectly fine (after navigating, remove content from DOM and loads them on navigating). So is it a .NET problem, or am I doing something wrong?

It is worth mentioning that I put SectionOutlet in the App.razor file at the end of <body> tag before </body>.

<!--begin::Page Javascripts-->
<SectionOutlet SectionName="Scripts"/>
<!--end::Page Javascripts-->

</body>

I call it like this:

<SectionContent SectionName="Scripts">Some s files</SectionContent>

Solution

  • SectionContent is not reactive Once it renders content into a SectionOutlet it doesn’t update it again when navigating between pages
    If you load a page with the script (/AddProduct), it works fine. But if you start from a different page and then navigate, the script doesn’t load. Also, the scripts aren’t removed when navigating away they just stay in the DOM.

    Use HeadContent if your script can go into the <head>, wrap it in <HeadContent> in your page/component. It handles cleanup and re-render on navigation.

    <HeadContent>
        <script src="quill.min.js"></script>
    </HeadContent>
    

    If you are using .NET 7.0+ use Javascript Isolation.

    https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-8.0#javascript-isolation-in-javascript-modules