This code has been working just right in a blazor web assembly, embedded in a razor pages page, using .net 5.0 and .net 6.0. I had to upgrade to .net 7.0, by altering the framework in razor pages and blazor projects' properties, to fix a big something else and now it doesn't work. The onclick event is just not being detected.
<p>@(Myawesomevariable)</p>
<button @onclick="Myawesomefunction">Myawesomebutton</button>
@code
{
private int Myawesomevariable = 0;
private void Myawesomefunction()
{
Myawesomevariable++;
}
}
What th' flip?
Okay, you lucky people, here's the fix.
In .net 7.0, first create blazor webassembly solution from the visual studio template, with a client, a server and a shared project.
From the client project, wwwroot
folder, delete the index.html
file.
From the client project, delete these two lines in the program.cs
file:
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
Create a new blazor server project using the visual studio template and copy the _Host.cshtml
file from the blazor server project's pages
folder, to your project's pages
folder and remove the following lines:
<link href="css/site.css" rel="stylesheet" />
<link href="<THE PROJECT NAMESPACE>.styles.css" rel="stylesheet" />
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
and
<script src="_framework/blazor.server.js"></script>
Replacing them with:
<link href="css/app.css" rel="stylesheet" />
<link href="<YOUR PROJECT NAMESPACE>.Client.styles.css" rel="stylesheet" />
<component type="typeof(HeadOutlet)" render-mode="WebAssemblyPrerendered" />
and
<script src="_framework/blazor.webassembly.js"></script>
Create a new razor pages project and copy the following files from the razor pages pages
folder to your projects pages
folder:
Pages/Shared/_Layout.cshtml
Pages/Shared/_Layout.cshtml.css
Pages/_ViewImports.cshtml
Pages/_ViewStart.cshtml
In the imported _Host.cshtml
file, edit the namespace to
@namespace <YOUR PROJECT NAMESPACE>.Server.Pages
and add a reference to the client project
@using <YOUR PROJECT NAMESPACE>.Client
Finally, remove any references to blazor.server.js
and make sure every blazor pages calls the blazor.webassembly.js file
.
<script src="_framework/blazor.server.js"></script>
I now have a .net 7.0 razor pages project, with blazor components embedded in different pages AND the onclick event handler works.