Live Chat Icon For mobile
Live Chat Icon

How do I intercept routing in Blazor before it navigates?

Platform: Blazor| Category: General

The routing interception concept is sometimes used to restrict user access to some page or link if they did some work or made some changes on a specific page.
In the following code, you can use the NavigateTo() method to intercept routing inside the If condition. The routing happens according to the values passed in the condition.

  1. Create the class file [RouteData.cs].

     …………………. ..
    namespace BlazorApp.Data
    {
        public class RouteData
        {
            public string Textfield { get; set; }
        }
    }

  2. To register the RouteData class as a scoped service in Program.cs, you can use the following code snippet.
    [Program.cs]

    builder.Services.AddScoped<BlazorServerApp.Data.RouteData>();

  3. Add the following code to the [Index.razor] page.

     @page "/" 
    @inject Data.RouteData RouteData
    <p>Type the text below to allow Home page intercepting</p>
    <textarea @bind="RouteData.Textfield"></textarea>

  4. Check the condition and allow the navigation process in the [NavMenu.razor] page as shown.

    @inject NavigationManager NavigationManager
    @inject {Your App name}.Data.RouteData RouteData
    <div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
        <ul class="nav flex-column">
            <li class="nav-item px-3">
                <NavLink class="nav-link" @onclick="Navigate" Match="NavLinkMatch.All">
                    <span class="oi oi-home" aria-hidden="true"></span> Home
                </NavLink>
            </li>
                      ……………………. . .
        </ul>
    </div>
    @code {
        private bool collapseNavMenu = true;
        private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;
        private void ToggleNavMenu()
        {
            collapseNavMenu = !collapseNavMenu;
        }
               private void Navigate()
        {
            if (RouteData.Textfield == null)
            NavigationManager.NavigateTo("");
        }
    ………………… . . .

  5. Output

    Home page routing is intercepted when you type text in the text area. When the text area value is null, the app navigates to the home page.

    View Sample in GitHub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.