blazorblazor-server-sideasp.net-core-8

ASP.Net Core 8.0 MVC Blazor button element not working properly


I attempted to implement Blazor in my ASP.NET Core MVC application. When I try to click a button, it doesn't call the right method and doesn't do anything.

<button @onclick="UpdateHeading">
Update heading
</button>

@code {
    private HubConnection? hubConnection;
    private List<string> Messages { get; set; } = new List<string>();
    private string? UserName { get; set; }
    private string? Message { get; set; }
    private string headingValue = "Initial heading";

    public void UpdateHeading()
    {
        headingValue = "Updated Heading"; // Change heading value
    }

    public async ValueTask DisposeAsync()
    {
        if (hubConnection is not null)
        {
            await hubConnection.DisposeAsync();
        }
    }
}

I using these elements in Chat.razor file - it is in Mweb/Components folder with _Imports.razor file:

@using Microsoft.AspNetCore.SignalR.Client
@using Microsoft.AspNetCore.Components.Web
@inject NavigationManager Navigation

The Chat.cshtml file in the Pages folder:

@page
@model MWeb.Pages.ChatModel
@using MWeb.Components

@{
   Layout = "_Layout_Social_Panels";
   ViewData["Chat"] = "Chat";
}

@(await Html.RenderComponentAsync<MWeb.Components.Chat>(RenderMode.ServerPrerendered))

@* <component type="typeof(MWeb.Components.Chat)" render-mode="ServerPrerendered" /> *@

I see the following error in the debug console:

[2024-11-24T13:40:32.856Z] Information: Normalizing '_blazor' to 
'https://localhost:7291/_blazor'.
[2024-11-24T13:40:32.910Z] Information: WebSocket connected to 
wss://localhost:7291/_blazor?id=AA9bPvdFlmy2TDbiKCsYeQ.
[2024-11-24T13:40:32.969Z] Error: Connection disconnected with error 'Error: Server 
returned an error on close: Connection closed with an error.'.
Error: Server returned an error on close: Connection closed with an error.
Stack trace:
 >  at Xt._processIncomingData 
(https://localhost:7291/_framework/blazor.server.js:1:58755)
 >    at Xt.connection.onreceive 
(https://localhost:7291/_framework/blazor.server.js:1:51920)
 >    at s.onmessage (https://localhost:7291/_framework/blazor.server.js:1:80026)
'MWeb.exe' (CoreCLR: clrhost): Loaded 'C:\Program 
Files\dotnet\shared\Microsoft.NETCore.App\8.0.10\System.Buffers.dll'. Skipped loading 
symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Uncaught Error Error: Server returned an error on close: Connection closed with an 
error.
at _processIncomingData (localhost꞉7291/_framework/blazor.server.js:1:58755)
at Xt.connection.onreceive (localhost꞉7291/_framework/blazor.server.js:1:51920)
at s.onmessage (localhost꞉7291/_framework/blazor.server.js:1:80026)
SecurityError: Cannot access rules
Stack trace:
 >  at s (https://localhost:7291/_vs/browserLink:54:500)
 >    at t (https://localhost:7291/_vs/browserLink:54:594)
 >    at i (https://localhost:7291/_vs/browserLink:54:862)
 >    at l (https://localhost:7291/_vs/browserLink:54:878)
 >    at g (https://localhost:7291/_vs/browserLink:54:3648)

For the _framework/blazor.server.js I can reach, and I added in the layout file.

Additional information: if I create the

protected override async Task OnInitializedAsync() 

method, it will be called and will work in the chat.razor file. For the rendermode I cannot set InteractiveServer, because it indicates it is missing..

If anyone has experienced the same issue and found a solution, please let me know.


Solution

  • It can work fine in my side, you could step by step to check your code:

    1. Create a Components folder in the root project, assume your project named MWeb.

    2. Add an imports file(_Imports.razor) in MWeb/Components folder:

      @using System.Net.Http
      @using Microsoft.AspNetCore.Authorization
      @using Microsoft.AspNetCore.Components.Authorization
      @using Microsoft.AspNetCore.Components.Forms
      @using Microsoft.AspNetCore.Components.Routing
      @using Microsoft.AspNetCore.Components.Web
      @using Microsoft.AspNetCore.Components.Web.Virtualization
      @using Microsoft.JSInterop
      
    3. In the project's layout file (Pages/Shared/_Layout_Social_Panels.cshtml in Razor Pages apps:

      Add the following <base> tag to the <head> element:

      <head>
          <base href="~/" />
      //.....
      

      Add a tag for the blazor.server.js script immediately before the Scripts render section (@await RenderSectionAsync(...))

      //.....
      <script src="/_framework/blazor.server.js"></script>
      @await RenderSectionAsync("Scripts", required: false)
      
    4. Register the Blazor Server services in Program.cs where services are registered:

      builder.Services.AddServerSideBlazor();
      
    5. Add the Blazor Hub endpoint to the endpoints of Program.cs where routes are mapped. Place the following line after the call to MapRazorPages (Razor Pages):

      app.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}");
      app.MapRazorPages();
      
      app.MapBlazorHub();
      
      app.Run();
      

    Then use your razor component chat.razor in MWeb/Components folder:

    <button @onclick="UpdateHeading">
    Update heading
    </button>
    
    @code {
        private HubConnection? hubConnection;
        private List<string> Messages { get; set; } = new List<string>();
        private string? UserName { get; set; }
        private string? Message { get; set; }
        private string headingValue = "Initial heading";
    
        public void UpdateHeading()
        {
            headingValue = "Updated Heading"; // Change heading value
        }
    
        public async ValueTask DisposeAsync()
        {
            if (hubConnection is not null)
            {
                await hubConnection.DisposeAsync();
            }
        }
    }