Home > Enterprise >  Blazor Server OnAfterRenderAsync not firing for components
Blazor Server OnAfterRenderAsync not firing for components

Time:10-05

I am trying to integrate blazor server into an existing MVC project, and am a little confused as to the requirements for getting my components to call OnAfterRenderAsync().

I have the following simple Index.razor page for testing made up of the following:

@page "/Index"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button  @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        return base.OnAfterRenderAsync(firstRender);
    }

    private void IncrementCount()
    {
        currentCount  ;
    }
}

If I navigate directly to /Index the OnAfterRenderAsync method is hit just fine. But if I render Index.razor as a component in my cshtml like this: @(await Html.RenderComponentAsync<Index>(RenderMode.ServerPrerendered ))

Then the OnAfterRenderAsync() is not hit.

I have MapBlazorHub() in my Startup.cs and <script src="~/_framework/blazor.server.js"></script> in my _Host.cshtml.

Have I missed a step somewhere or is this behavior by design in Blazor Server, and if so, is there some workaround? I need some reusable blazor components to be able to work with JS libraries that were implemented in the MVC project, so I need those components to be able to call OnAfterRenderAsync() without going directly to the page URL

CodePudding user response:

After inspecting the sources in developer tools I saw that the folder for _framework was not present in my component. Even though I could navigate to https://myurl/_framework/blazor.server.js and saw the file was present in my project, my component didn't have access to it. adding the script tag <script src="~/_framework/blazor.server.js"></script> directly to my cshtml file that was rendering my Blazor component fixed my issue.

  • Related