Add blazor to existing asp.net core project
If you want to add server-side Blazor to your existing ASP.NET Core application, its simple and easy. C# code lovers will enjoy working in mixed mode with html/c# code in single/multiple pages. Its compelety fun to add blazor into existing views with other html components. I will guide you in this article step by step how to integrate it and reuse components anywhere in application.
Pre-requisites.
.NET Core 3.1
Visual Studio 2019 16.3+
Add follow configuration lines into sections.
- ConfigureServices
services.AddServerSideBlazor(o => o.DetailedErrors = true);
- app.UseEndpoints(endpoints =>
endpoints.MapBlazorHub();
- In Layout page before body tag 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 lets put component into any view and add 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 out.
That's all you need to do, enjoy blazor ui.
Regards
Qaiser Mehmood Mughal