Creating First Application in Blazor from scratch

Creating First Application in Blazor from scratch
Let us create your First Application in Blazor in Visual Studio 2019. The procedure is to create an ASP.NET Core project and configure it to use Blazor. Note that the Visual Studio has a Blazor Template option which automatically configures a new project for Blazor. But since I have to introduce all the files structures of Blazor and their workings to you, therefore I will be creating this application from empty stage. You are going to love this approach so be with this tutorial till the end.

Create a new Blazor Application

Start with Create a new Project and select the template called ASP.NET Core Web Application like shown by the below image.

ASP.NET Core Web Application

In the next window which says – Configure your new project, give the project name as BlazorFirstApp and select the location in the disk for the project files. Then click the Create button. See below image:

configure your new project

Next, you will get the Create a new ASP.NET Core web application window. Here you select the following 3 things:

  • .NET Core
  • ASP.NET Core 5.0
  • ASP.NET Core Empty

Finally click the Create button. The project will be created in a few seconds time and you are ready to use and unleash the power of the Blazor technology.

I have marked all these steps in the below image:

Create a new ASP.NET Core web application

Configuring ASP.NET Core application for Blazor Server

The application is already created and if you see the Solution Explorer window you will notice there are only a few files. Check the screenshot given below.

Solution Explorer

Now let us start Configuring the application for Blazor Server. The first step is to add the services and middleware to the Startup class. Start by adding services.AddRazorPages() inside the ConfigureServices method. It is needed since Blazor needs Razor Pages support to work.

Next, add services.AddServerSideBlazor() inside the ConfigureServices method. This adds Server-Side Blazor services to the service collection.

Next add endpoints.MapBlazorHub() inside the app.UseEndpoints() method of the Configure method. This integrates the Blazor with ASP.NET Core Endpoint Routing. This will also let SignalR which is the part of ASP.NET Core that handles the persistent HTTP request to work properly.

I have shown these things in the below highlighted code of the Startup.cs class.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorFirstApp
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

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

Razor Components

Blazor apps are built using components. These components are implemented in Razor Component files and these files have a .razor extension. In razor component you write your Blazor codes. They typically contains:

  • The razor component file contains a mixture of HTML and C# and uses the familiar Razor syntax.
  • C# code is defined in an @code block

The below given code is of a razor component called count.razor.

@page "/count"

<h1>Count</h1>

<p>Current count: @currentCount</p>

<button @onclick="IncrementCount">Click to Increase Count</button>

@code {
    private int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}

The first line – @page "/count" specifies it’s URL which will invoke it. In this case it is https://localhost:/count. The next 3 lines contains the HTML which this razor component contains. There is a button which calls a C# function named IncrementCount, on clicking this button the counter variable called currentCount increases it’s value by one.

The value of this counter variable is shown inside a paragraph tag.

<p>Current count: @currentCount</p>

All the C# codes are contained inside the @code block.

I have written a complete tutorial on How to use Razor Components in Blazor, you should read it as it have in-depth knowledge.

Blazor Imports File – “_Imports.razor”

Blazor Imports File let you to import commonly used namespaces at one place so that you don’t have to import them separately on each Razor component that needs them.

Right click on the project name in the Solution Explorer and select Add ➤ New Item. You will see an Add New Item window opens up and it contains a lot of different files that can be selected. Here select Razor Component and name it as _Imports.razor. Click the Add button to create this file in the application’s root folder.

Blazor Imports File

Once the Blazor Imports file is created simply add the following 2 codes lines to it:

@using Microsoft.AspNetCore.Components.Routing
@using BlazorFirstApp.Shared

The first line is importing the Routing feature and is used for rendering and mapping routes to components. This is needed so that the urls are mapped to different razor components.

The second line imports the contents of Shared folder. I will be taking it in just a moment.

Some points to remember:

  • 1. You can add a file called _Imports.razor to every folder of the application. The .NET will include the directives specified in the Blazor Imports File for all of the Razor templates that lie in the same folder or any of it’s subfolders.
  • 2. You can also specify layouts in the Blazor Imports file for razor component. For example – @layout MyLayout ensures that all of the components in a folder and subfolder uses MyLayout.

Blazor Router component – “App.razor”

Blazor uses ASP.NET Core Routing system for selecting component based on URLs. So Blazor applications responds to changes in the URL by displaying different Razor Components. To get started, add a new Razor Component on the application’s root folder and call it App.razor. Add the following given codes to it:

<Router AppAssembly="@typeof(Startup).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

Check the below image which shows the location of App.razor file:

App.razor

Let me explain you all about the above code in details. First, we need to specify the name of the .NET AppAssembly to use which in most cases is the current assembly:

…
<Router AppAssembly="@typeof(Startup).Assembly">
…

Next, defining the “Found” and “NotFound” sections. In the Found section provide the contents to display when the match to the requested route (i.e. URL) is found. Similarly, in the NotFound section provide the contents to display when no match is found for the requested route.

In reality the Router, Found, NotFound, RouteView etc are all Blazor in-built components that performs specific tasks provided to them.

I have defined the “Found” section as shown below:

<Found Context="routeData">
    <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>

The context property is set to routeData – Context="routeData". Inside it there is RouteView section which receive the route data (set as RouteData="@routeData") and default layout (set as DefaultLayout=”@typeof(MainLayout)”).

The RouteView populates the matching component’s contents inside the layout (UI). I have defined this layout to be MainLayout in this case. Layout basically contains the common areas of the app like the header and footer of the website. These common areas can be shown from the layout instead of defining them again and again in different component of the Blazor app. This approach greatly reduces code redundancy.

Note : A razor component can override this DefaultLayout by providing another layout like @layout AnotherLayout. I will create the main layout file in just a moment.

Coming to the “NotFound” section which is given as:

<NotFound>
    <LayoutView Layout="@typeof(MainLayout)">
        <p>Sorry, there's nothing at this address.</p>
    </LayoutView>
</NotFound>

It just calls component called LayoutView which sets the same layout with a sorry message, and it is shown in case of no matching for the routes.

You can also use a different layout for the not found section, if you wish to.

Endpoint Routing integration in Blazor

Blazor works with ASP.NET Core Endpoint Routing. I have already integrated it by adding the code – endpoints.MapBlazorHub() inside the app.UseEndpoints method of the Configure method of Startup.cs class.

app.UseEndpoints(endpoints =>
{
    endpoints.MapBlazorHub(); // integrates blazor with endpoint routing
});

Now you can call any Razor component from inside the ASP.NET Core Controller’s views or Razor pages.

Fallback Route “_Host.cshtml”

In case if we are using a standalone Blazor app, like in our case where there are only Components and no Views or Razor Pages, then we have to use a Fallback Route which will call a Razor page by the name of _Host.cshtml. The fallback route has a very low priority in routing matching and so this route is initiated when other routes didn’t match.

Because of this we can now also add ASP.NET Core MVC areas and razor pages in out Blazor app (if we wish to), and they will not interfere with the Blazor Server components.

So go forward and add the code line – endpoints.MapFallbackToPage("/_Host") inside the app.UseEndpoints() to provide a Fallback Route to the Blazor App.

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");
});

Next, create a new Razor View called _Host.cshtml inside the Pages folder of your app. Add the following code to it:

@page "/"
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Blazor First App</title>
    <base href="~/" />
</head>
<body>
    <component type="typeof(BlazorFirstApp.App)" render-mode="ServerPrerendered" />

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

Explanation of Codes : The code is an HTML Page with razor mark-up. It forms the top level of an HTML page markup. Notice the DOCTYPE, html, head and body tags present in the code.

It calls Blazor Router component which is defined by the App.razor as shown below:

<component type="typeof(BlazorFirstApp.App)" render-mode="ServerPrerendered" />

I have already explained App.razor component’s working in the above section. In short, the respective layouts will be called.

The render-mode attribute sets the RenderMode Enum’s value to ServerPrerendered. It tells to render the component into static HTML and includes a marker for a Blazor server-side application. The HTML content of the component is sent again over the persistent HTTP connection.

Other things to note here are:

  • 1. @page "/" specifies the URL of this component.
  • 2. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers imports the tag helper in the component. You can check my tutorial called Introduction to Tag Helpers in ASP.NET Core to know more about this topic.
  • 3. @{ Layout = null;} specifies that this component will “not” have a parent layout.
  • 4. The script element specifies the name of the JavaScript file that establishes the SignalR connection with the server. Note that you don’t have to add this JavaScript code to the project.
    <script src="_framework/blazor.server.js"></script>
    

Other things in this component are just HTML tags.

Blazor Layouts

You must have noticed that in a website or an app, the header and footer elements remain same through the app. The things which are kept on the header and footer elements are logos, copyright text, navigation menu, etc and these never change.

The best approach would be to keep the header and footer elements in a common area called layout files and all the component of the Blazor app should call these layout files and show up these common areas (header & footer) on their respective places. Check the below given illustration.

Blazor Layout

Since the layout is shared with other components therefore the layout file is kept inside the Shared folder. The Shared folder is kept just inside the root folder of the APP. If you haven’t created it till now so first create it by right clicking the name of the app and selecting Add ➤ New Folder then name this folder as “Shared”.

Next, inside this shared folder create a new razor component called MainLayout.razor, and add the below code to it:

@inherits LayoutComponentBase

<header>
    <nav>
        <a href="/">Home</a>
        <a href="about">About</a>
        <a href="contact">Contact</a>
    </nav>
</header>

@Body

<footer>
    All Rights Reserved
</footer>

Check the below image which shows this newly created layout file’s location inside the shared folder.

MainLayout.razor
The reason I specifically named this layout file as MainLayout.razor is because in my Blazor Router component – “App.razor”, I had defined this name as the name of the layout file.
<Found Context="routeData">
    <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
You can name the layout anything but remember to change the DefaultLayout attribute’s value in the “App.razor” if you do so.

Since I goanna keep my header and footer in this file. Therefore, notice the header and footer html tags. I have kept a navigation menu in the header while the footer shows just a simple copyright message.

The important thing to note is that the layout must inherit from the LayoutComponentBase which is done by the code – @inherits LayoutComponentBase.

The Razor syntax @Body specifies the location in the layout where the component’s content is rendered. Note – I have put the @Body between the header and the footer. Basically, this means, when the component is rendered on the browser then:

  • First the Fallback Route which is _Host.cshtml is called. Note that it forms the top level html tags of the html page like DOCTYPE, head, body, etc.
  • Next from the _Host.cshtml the Blazor Router component which is App.razor is called. This in turn will call the default layout called MainLayout.razor. The default layout will form the header and footer sections of the html page.
  • Inside the header & footer sections the component’s code will show.

I have illustrated this in the below image.

blazor page structure

And this way the layout will do it’s work properly in the app.

Create a new Razor Component

I have already done all the Blazor Configurations and the app is ready to be added with new Razor Components (remember Blazor Components are made in razor component files).

So, let us start by adding a new simple Razor Component which just shows a hello message.

Right click on the Pages folder and create a new razor component file and name it Index.razor. Add the following code to this file:

@page "/"

<h1>Hello</h1>

<p>Welcome to your new app.</p>

The first line uses @page directives for declaring the URLs for which this Razor Component will be displayed. I have declared the URL as “/” so it’s route in my case becomes https://localhost:44366/, the port may be different in your case.

Now run your project and you will see the component get’s displayed, check below image:

Blazor Component

Notice it also shows the header and footer sections which it gets from the layout file.

More than one route can be defined for a component. Like, see the below code where I have defined 3 routes for this component.

@page "/"
@page "/Welcome"
@page "/Hello/Jack"

<h1>Hello</h1>

<p>Welcome to your new app.</p>

So now this component can be opened with 3 routes which are:

  • 1. https://localhost:44366/
  • 2. https://localhost:44366/Welcome
  • 3. https://localhost:44366/Hello/Jack

Integrating Bootstrap in Blazor App

The component which I made has a very basic design. I can modernize it by integrating Bootstrap framework into the Blazor App and update the design of the component by using Bootstrap CSS.

If you have come across the term Bootstrap for the first time then I recommend you to have a reading of this this introductory article – What is Bootstrap and Why you should use it in Web Development

You can Install Bootstrap framework from LibMan inside the wwwroot/lib/bootstrap folder.

Now you can start using Bootstrap in you App. So, open the _Host.cshtml file and add a link to Bootstrap CSS in the head section. Then put the component tag inside a div having CSS class called “m-1 p-1”. Check the below highlighted code for these changes:

@page "/"
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Blazor First App</title>
    <base href="~/" />
    <link href="~/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="m-1 p-1">
        <component type="typeof(BlazorFirstApp.App)" render-mode="ServerPrerendered" />
    </div>

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

Next, edit the MainLayout.razor file to include the Bootstrap CSS like shown by the highlighted code below:

@inherits LayoutComponentBase

<header class="bg-dark text-white">
    <nav class="text-center">
        <a href="/">Home</a>
        <a href="about">About</a>
        <a href="contact">Contact</a>
    </nav>
</header>

<div class="p-4">
    @Body
</div>

<footer class="bg-success">
    All Rights Reserved
</footer>

Next, update the Index.razor code as shown below:

@page "/"

<h1 class="bg-info text-white">Hello</h1>

<p>Welcome to your new app.</p>

Now run your project and you will see new design of the index page which is shown by the below given image:

Bootstrap applied design
Creating an Advanced Feature in Blazor

Now let us create a feature that will work as shown by the below video:

blazor advanced feature

In this feature I am showing a list of people and their cities in a html table. There is a select control, given at the bottom, so that user can select the city and then all the people who are in the selected city are highlighted.

Start by importing Microsoft.AspNetCore.Components.Web namespace in the _Imports.razor file so that browser events are handled by Blazor. The modified code of _Imports.razor file is shown in highlighted manner.

@using Microsoft.AspNetCore.Components.Routing
@using BlazorFirstApp.Shared
@using Microsoft.AspNetCore.Components.Web

Next add the below given code in the index.razor file.

@page "/"

<h1 class="bg-info text-white">Hello</h1>

<table class="table table-sm table-bordered table-striped ">
    <thead>
        <tr>
            <th>Name</th>
            <th>City</th>
        </tr>
    </thead>
    <tbody>
        @foreach (People p in peopleList)
        {
            <tr class="@GetCSS(p.City)">
                <td>@p.Name</td>
                <td>@p.City</td>
            </tr>
        }
    </tbody>
</table>
<div class="form-group">
    <label for="city">City</label>
    <select name="city" class="form-control" @bind="SelectedCity">
        <option disabled selected>Select City</option>
        @foreach (string city in Cities)
        {
            <option value="@city" selected="@(city == SelectedCity)">
                @city
            </option>
        }
    </select>
</div>

@code {
    public class People
    {
        public string Name { get; set; }
        public string City { get; set; }
    }

    public IEnumerable<People> peopleList => new List<People> {
                new People { Name = "Jack Sparrow", City = "New York" },
                new People { Name = "Bruce Wayne", City = "Gotham" },
                new People { Name = "Clark Kent", City = "Metropolis" },
                new People { Name = "Donald Trump", City = "New York" },
                new People { Name = "Vladimir Putin", City = "Moscow" },
                new People { Name = "Chipper Jones", City = "Beijing" },
                new People { Name = "Cristiano Ronaldo", City = "Funchal" }
            };

    public IEnumerable<string> Cities => peopleList.Select(l => l.City).Distinct();

    public string SelectedCity { get; set; }
    public string GetCSS(string city) => SelectedCity == city ? "bg-info text-white" : "";
}

Working details : The list of people are shown by html table. I have used foreach loop for looping through this list of people. Not to mention these are kept by a C# variable called by the name – “peopleList”.

…
<tbody>
    @foreach (People p in peopleList)
    {
        <tr class="@GetCSS(p.City)">
            <td>@p.Name</td>
            <td>@p.City</td>
        </tr>
    }
</tbody>
…

The tr tag calls a C# function by the name of GetCSS() and passes to it the city of the current person that is being undergoing binding. This C# function then checks if the city of the person is same as that stored in the variable called SelectedCity, and in that case the Bootstrap classes “bg-info text-white” are applied to the “tr” tag and so it is highlighted.

The SelectedCity variable’s value is updated everytime the city is changed on the select control.

The select control has been applied with the attribute named @bind which provides the data binding with the variable SelectedCity.

<select name="city" class="form-control" @bind="SelectedCity">

So that when a new value of the city is selected on the select control then html table is once again bind and GetCSS() function is called which shown the respective rows in highlighted manner.

Run the app and check how it works.

NavLink is an in-built component in Blazor and is used for creating anchor tags for navigation. The NavLink component has added advantage over normal anchor tag as it toggles an “active” CSS class based on whether it’s href matches the current URL in the browser. With this, you can assign a color to this active class and your users will know which URL they are currently in.

Another great advantage of NavLink component is that it renders anchor elements that are wired into the routing system.

For example, by adding the following NavLink Component on a Razor Component:

<NavLink href="/City">City</NavLink>

The following anchor tag is formed:

<a href="https://localhost:44366/City">City</a>
If the user visits the City URL then NavLink performs the match and this anchor tag will be applied with an active CSS class. That is it becomes:
<a class="active" href="https://localhost:44366/City">City</a>

You can provide some color (like red) to this css and user will see a red color link when he/she is on the same page which the link’s href targets.

.active {
    color: red;
}

You can assign Match attribute to the NavLink to change the URL match procedure. There can be 2 values to it:

  • NavLinkMatch.All: The NavLink is active when the entire current URL matches. Ex – Match="NavLinkMatch.All". Take for example https://localhost:44366/City will be matched while https://localhost:44366/City/NYC & https://localhost:44366/Moscow will be not be matched for <NavLink href="/City" Match="NavLinkMatch.All">City</NavLink>.
  • NavLinkMatch.Prefix (default): The NavLink is active when any prefix of the current URL is matched. Ex – Match="NavLinkMatch.Prefix". Take for example https://localhost:44366/City, https://localhost:44366/City/NYC will be matched for <NavLink href="/City" Match="NavLinkMatch.Prefix">City</NavLink>. https://localhost:44366/Moscow will not be matched.

Left Navigation using NavLink

Let us create a left navigation bar feature by using NavLink component. So create a new Razor Component called MyNav.razor inside the Shared folder of the app. Add the following code to it:

<style>
    .active {
        color: red;
    }
</style>

<div class="p-3 mb-2 bg-warning text-dark">
    <h3 class="bg-info text-white">Links</h3>
    <ul class="nav flex-column">
        <li class="nav-item px-3">
            <NavLink href="/" Match="NavLinkMatch.All">
                Index
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink href="/City">
                City
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink href="/Country">
                Country
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink href="/Continent">
                Continent
            </NavLink>
        </li>
    </ul>
</div>

The component has 4 li tags that contains NavLink component. So, it will have 4 anchor tags that will link to Index, City, Country and Continent components. For the first NavLink I have used Match="NavLinkMatch.All", this will match the URL without any component i.e. https://localhost:44366. The other NavLinks do not have a Match attribute so the default one – NavLinkMatch.Prefix will automatically use. I have also added red color for the “active” css under the style element.

Now call this MyNav.razor component from the default layout of the app which is MainLayout.razor and align it to the left so that it looks like a left navigation. The left alignment will be done using Bootstrap CSS.

Below I have marked the updated code of the MainLayout.razor that is calling the MyNav.razor and aligning it to the left side.

@inherits LayoutComponentBase

<header class="bg-dark text-white">
    <nav class="text-center">
        <a href="/">Home</a>
        <a href="about">About</a>
        <a href="contact">Contact</a>
    </nav>
</header>

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-3">
            <MyNav />
        </div>
        <div class="col-sm-9">
            @Body
        </div>
    </div>
</div>

<footer class="bg-success">
    All Rights Reserved
</footer>

Next add the Razor Component called City, Continent and Counter to the Pages folder. They don’t perform any task except displaying their name under h1 tag.

City
@page "/City"

<h1 class="bg-info text-white">Washington DC</h1>

@code {

}
Country
@page "/Country"

<h1 class="bg-info text-white">USA</h1>

@code {

}
Continent
@page "/Continent"

<h1 class="bg-info text-white">North America</h1>

@code {

}

Now run the app and check it’s working. The below video shows how it works, notice the color of the links becomes red when I am click on them.

ActiveClass – It is another attribute of NavLink component which specifies one or more CSS classes that the anchor element (created by the NavLink component) will be added to when the current URL matches the href attribute value. So if you want another CSS called “otherone” to be applied with “Active” CSS during match then add – ActiveClass="otherone".

When you have to create navigation links programmatically i.e. in Blazor events, properties or inside C# code block then using the NavigationManager class. The NavigationManager class provides programmatic access to navigation and is provided as a service from Dependency Injection feature. It is received by Razor Components using the [Inject] attribute.

The below code provides an object of NavigationManager class to the NM variable using dependency injection.

[Inject] 
public NavigationManager NM { get; set; }

Next, I can add a button that on clicking navigates the user to another URL. Check the code below:

<button class="btn btn-primary" @onclick="NavigateUser">Country</button>

public void NavigateUser() => NM.NavigateTo("/Country");

Now let us use the NavigationManager class and create a button inside the MyNav.razor component. When this button is clicked the user is navigated to country component. Check the highted code below which shows the necessary changes done to the MyNav.razor component.

<style>
    .active {
        color: red;
    }
</style>

<div class="p-3 mb-2 bg-warning text-dark">
    <h3 class="bg-info text-white">Links</h3>
    <ul class="nav flex-column">
        <li class="nav-item px-3">
            <NavLink href="/" Match="NavLinkMatch.All">
                Index
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink href="/City">
                City
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink href="/Country">
                Country
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink href="/Continent">
                Continent
            </NavLink>
        </li>
    </ul>

    <button class="btn btn-primary" @onclick="NavigateUser">Country</button>
</div>

@code{

    [Inject]
    public NavigationManager NM { get; set; }

    public void NavigateUser() => NM.NavigateTo("/Country");

}

This is how it looks:

NavigationManager class blazor

Some useful NavigationManager Members are listed in the below table:

Name Description
Uri This property returns the current URL.
LocationChanged This is an event which is fired when the location changes.
NavigateTo() This method navigates to a specific URL. It can accept 2 parameters – first is the navigate URL while the second is a bool type parameter. When you pass true then browser will be forced to load a new page. Otherwise false is the default value where navigation Is performed without sending a new HTTP request.
ToAbsoluteUri This method Converts a relative URI into an absolute URI.
ToBaseRelativePath This method returns a relative URL of the URL that is passed to it.

You can download this app by clicking the below link:

Download

Summary

Congratulations you have successfully created your first Blazor app and I hope you must have understood how razor components work and how you can create really interesting Blazor Features with very little C# codes.

Share this article -

yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee

Comments

  1. Peter Browne says:

    I cannot Add > New Item > Razor Component to the Solution Explorer. I only have Type: General Items and C# category is not available.

    This is having gone to Tools > Import and Export and added Visual C# and restarted Visual Studio.

    Visual Studio is up to date at v16.8.3.

    1. yogihosting says:

      Hello Peter,

      You will need to add ASP.NET Core packages. Download Visual Studio installer and then run it. It will show what packages you had and what you are missing. Add the ASp.NET Core ones, this will probably solve your problem.

      Thank you.

  2. Joel W Zinn says:

    I am following along your article and when I get to the first part where the bootstrap stuff is added and I change the styles of the pages, the styles are now found. I get:
    bootstrap.min.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)

    I am also getting:
    blazor.server.js:1 Failed to load resource: the server responded with a status of 404 (Not Found)
    I have verified the files did come down from libman process. I have gone through this twice with the same result.
    Any ideas?

    1. yogihosting says:

      Hello Joel,

      The Bootstrap will be added to wwwroot folder of your app. If Libman is not adding the Bootstrap to your app then try closing Visual Studio and restarting your PC, and then try again once more. This will certainily solve your problem.

      Moreover you can simply download Bootstrap package from Boostrap site and paste that package to your “wwwroot” folder manually.

      Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *