Home > front end >  I included Blazor component to my ASP.NET Core 6 MVC project but it doesn't work
I included Blazor component to my ASP.NET Core 6 MVC project but it doesn't work

Time:06-02

enter image description hereIt displays but doesn't work button click.

Index.cshtml:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.css">
</head>
<body>
<component type="typeof(ShiftsEditor)" render-mode="WebAssemblyPrerendered"/>
</body>
</html>

ShiftsEditor.razor (it is the test component):

@page "/ShiftsEditor"

<h3>ShiftsEditor</h3>
<p>@prgf</p>
<button @onclick="UpdateHeading">button</button>

@code {
    public string prgf = "str";

    public void UpdateHeading() => prgf = "content updated";
}

CodePudding user response:

You can check if the JS you are referencing in _Layout.cshtml is <script src="_framework/blazor.server.js"></script> or <script src="_framework/blazor.webassembly.js"></script>.

server.js needs to use render-mode="ServerPrerendered", and webassembly.js needs to use render-mode="WebAssemblyPrerendered".

Index.cshtml:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.css">
</head>
<body>
    <component type="typeof(ShiftsEditor)" render-mode="ServerPrerendered"/>
</body>
</html>

Add@using Microsoft.AspNetCore.Components and @using Microsoft.AspNetCore.Components.Web in razor.

ShiftsEditor.razor:

@page "/ShiftsEditor"
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web;

<h3>ShiftsEditor</h3>
<p>@prgf</p>
<button @onclick="UpdateHeading">button</button>
@code {
    public string prgf = "str";
    public void UpdateHeading() => prgf = "content updated";
}

_Layout.cshtml:

<base href="~/" />
<script src="_framework/blazor.server.js"></script>

Program:

builder.Services.AddServerSideBlazor();
app.UseEndpoints(endpoints =>
{
    endpoints.MapBlazorHub();
}

Test Result:

Before click:

enter image description here

After click:

enter image description here

  • Related