Codementor Events

Add blazor to existing asp.net core project

Published Aug 15, 2022Last updated Sep 09, 2022
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.

  1. ConfigureServices
    services.AddServerSideBlazor(o => o.DetailedErrors = true);
    

s1.png

  1. app.UseEndpoints(endpoints =>
    endpoints.MapBlazorHub();
    

s2.png

  1. In Layout page before body tag closed add js file reference
    <script src="_framework/blazor.server.js"></script>
    

s3.png

We are all set now to include existing or new blazor components.

s5.png
s4.png

@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

s6.png

  @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.

s8.png

That's all you need to do, enjoy blazor ui.

Regards
Qaiser Mehmood Mughal

Discover and read more posts from Qaiser Mehmood
get started