SteinTech
SteinTech

Reputation: 4068

implementing Blazor in an ASP.NET Core site - components don't render in views

I've followed every step in this article: https://waelkdouh.medium.com/integrating-blazor-components-into-existing-asp-net-core-mvc-applications-b1a2aec4ac1f

I've created a file named MyFirst.razor in the Components/Pages folder, but it doesn't render when referenced in Index.cshtml as .

Components.Pages/MyFirst.razor

 @page "/my-first"

<h3>Current count: @count</h3>

@code {
    private int count = 0;

    private void HandleClick()
    {
        count++;
    }
}

Views/Home/Index.cshtml

@using LC.BlazorTest.Components.Pages
   
<h1>Velkommen - blaze up</h1>

<MyFirst />

Index page source:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<meta content="width=device-width, initial-scale=1.0" name="viewport" />

<title>BlazorBlazor</title>

<link href="/IMAGE/fav-icon.png" rel="icon" type="text/CSS" />

<link href="/STYLE/Creator/Creator.css" rel="stylesheet" type="text/CSS" />


</head>
<body>
    <main role="main" class="pb-3">
        


<h1>Velkommen - blaze up</h1>

<MyFirst />

    </main>

    <script crossorigin="anonymous" src="/SCRIPT/Creator/Creator.js" type="application/JAVASCRIPT"></script>

<script crossorigin="anonymous" src="https://kit.fontawesome.com/c237ba9e1f.js" type="application/JAVASCRIPT"></script>



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

    
</body>
</html>

the tag hasn't changed.

Upvotes: 0

Views: 468

Answers (1)

Martin Drozd&#237;k
Martin Drozd&#237;k

Reputation: 381

Looks like you are trying to render a Blazor component into an MVC view. As far as I know, it is not that simple.

You may want to use the component tag helper to render Blazor components in cshtml views.

Unfortunately, MVC views are rendered once on the server, so you can not simply just put a component name like with your regular Blazor app.

You can prerender the component (it will remain static), use server-side rendering or client-side rendering (WebAssembly). It may be a little bit tricky tho since you mix multiple rendering styles together. In short, use

<component type="typeof(MyFirst)" render-mode="ServerPrerendered" />

instead of

<MyFirst />

when writing in cshtml files (MVC pages/views).

Checkout render modes or prerendering

Upvotes: 2

Related Questions