If you want to add server-side Blazor to your existing ASP.NET Core application, it's simple and easy. C# code lovers will enjoy working in mixed mode with html/c# code in single/multiple pages. It's completely fun to add blazor to existing views with other HTML components. I will guide you in this article step by step on how to integrate it and reuse components anywhere in the application.
Pre-requisites
- .NET Core 3.1
- Visual Studio 2019 16.3+
Add following configuration lines into sections
1. ConfigureServices
services.AddServerSideBlazor(o => o.DetailedErrors = true);
2. app.UseEndpoints(endpoints =>
endpoints.MapBlazorHub();
3. In Layout page before the body tag is closed add js file reference
<script src="_framework/blazor.server.js"></script>
We are all set now to include existing or new blazor components.
@using Microsoft.AspNetCore.Components.Web
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Now let's put component into any view and add a reference into div
@page
@using WebApplication2.Pages.Component
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<div class="text-center">
@(await Html.RenderComponentAsync<CountComponent>(RenderMode.Server))
</div>
So two main lines of code for magic anywhere in views.
@using WebApplication2.Pages.Component
@(await Html.RenderComponentAsync<CountComponent>(RenderMode.Server))
Here you will see the component.
That's all you need to do, enjoy c# code lovers.