Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current URL in a Blazor component

I need to know the URL of the current page in order to check if I have to apply a certain style to an element. The code below is an example.

    @using Microsoft.AspNetCore.Blazor.Services     @inject IUriHelper UriHelper     @implements IDisposable      <h1>@url</h1>     <nav>         <div class="nav-wrapper">             <a href="#" class="brand-logo">Blazor</a>             <ul id="nav-mobile" class="right hide-on-med-and-down">                 <li>                     <NavLink href="/" Match=NavLinkMatch.All>                         Home                     </NavLink>                 </li>                 <li>                     <NavLink href="/counter">                         Counter                     </NavLink>                 </li>                 <li>                     <NavLink href="/fetchdata">                         Fetch data                     </NavLink>                 </li>             </ul>         </div>     </nav>      @functions {          private string url = string.Empty;          protected override void OnInit()         {             url = UriHelper.GetAbsoluteUri();             UriHelper.OnLocationChanged += OnLocationChanged;         }          private void OnLocationChanged(object sender, LocationChangedEventArgs e)         {             url = newUriAbsolute;         }          public void Dispose()         {             UriHelper.OnLocationChanged -= OnLocationChanged;         }     } 

I used the same approach used in the NavLink component in the Blazor repository, but it did not work. Any ideas?.

like image 363
Carlos L. Avatar asked Apr 30 '18 14:04

Carlos L.


People also ask

How do you reference a component in Blazor?

To capture a component reference in Blazor, use the @ref directive attribute. The value of the attribute should match the name of a settable field with the same type as the referenced component. When the parent component is rendered, the field is populated with the child component instance.

How do I force a Blazor reload page?

A page is reloaded/refreshed automatically at a specified interval using “NavigationManager” in OnAfterRender() method. Here the NavigateTo(“url”, forceLoad: true) method, is used to force load the browser based on the URI.

How do I navigate to another page in Blazor?

You can redirect to a page in Blazor using the Navigation Manager's NavigateTo method. In the following code snippet, it will redirect to the home page when this page gets loaded. Similarly, you can call NavigateTo() method from NavigationManager class anywhere to redirect to another page.

Does Blazor have hot reload?

In Blazor apps, the framework triggers a Razor component render automatically. In MVC and Razor Pages apps, Hot Reload triggers a browser refresh automatically.


1 Answers

Use the Uri property from the NavigationManager class.

How it works

Get it from injection before using it on .razor pages:

@inject NavigationManager MyNavigationManager 

Or like this in a .cs file if you prefer the "code-behind" experience:

using Microsoft.AspNetCore.Components; ... [Inject] public NavigationManager MyNavigationManager {get; set;} 

Sample

@page "/navigate" @inject NavigationManager MyNavigationManager  <h1>Current URL</h1>  <p>@(MyNavigationManager.Uri)</p>  

More about navigation (NavigateTo, BaseUri, ToAbsoluteUri, ToBaseRelativePath, ... ) at: URI and navigation state helpers

NavigationManager cheatsheet

MyNavigationManager.Uri #> https://localhost:5001/counter/3?q=hi  MyNavigationManager.BaseUri #> https://localhost:5001/  MyNavigationManager.NavigateTo("http://new location") #> Navigates to new location  MyNavigationManager.LocationChanged #> An event that fires when the navigation location has changed.  MyNavigationManager.ToAbsoluteUri("pepe") #> https://localhost:5001/pepe  MyNavigationManager.ToBaseRelativePath(MyNavigationManager.Uri) #> counter/3?q=hi  Helper: AddQueryParm( "q2", "bye" ) // (*1) #> https://localhost:5001/counter/3?q=hi&q2=bye  Helper: GetQueryParm( "q" ) #> hi 

(*1) Net6 introduces GetUriWithQueryParameter. More info: Manipulate the query string from Blazor

Helpers code:

@code {      [Parameter]     public string Id { get; set; }      // Blazor: add parm to URL     string AddQueryParm(string parmName, string parmValue)     {         var uriBuilder = new UriBuilder(MyNavigationManager.Uri);         var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);         q[parmName] = parmValue;         uriBuilder.Query = q.ToString();         var newUrl = uriBuilder.ToString();         return newUrl;     }      // Blazor: get query parm from the URL     string GetQueryParm(string parmName)     {         var uriBuilder = new UriBuilder(MyNavigationManager.Uri);         var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);         return q[parmName] ?? "";     }  } 
like image 128
dani herrera Avatar answered Sep 29 '22 13:09

dani herrera