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, we 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. Add a new class to [Startup.cs].

    …………….. . 
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
                services.AddServerSideBlazor();
                services.AddSingleton<WeatherForecastService>();
                services.AddScoped <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 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.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

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

Please submit your question and answer.