The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

How to get the last part of the url as a string

posted on 30.1.2023 by Below Surface in "Blazor"

Let's say we want to render a link button to a page conditionally in our Blazor application. Because it would not make much sense to show this button on the page that it links to. We need a way to find out, if we currently are on this page or not.

Firstly we need to import the NavigationManager to our .razor file

@inject NavigationManager MyNavigationManager

Then within the bottom code block, we can add a boolean { get; set } that our conditional rendering will be based on.

private bool FaqPage { get; set; }

At last, we add the functionality:

// get the whole url
var FullUrl = MyNavigationManager.Uri;
// only takes whatever comes after the last "/"
var PageUrl = FullUrl.Substring(FullUrl.LastIndexOf("/" + 1);
// in our example, some links have a "#" with a string attached, to jump to a html id. so we need to clear that away
var PurePageUrl = PageUrl.Split("#")[0]; 
if (PurePageUrl == "faq")
   FaqPage = true;
  FaqPage = false;

Now, within the .razor HTML code above, we can conditionally render the button like this:

@if (!FaqPage)
  <a href="/faq">FAQ Page</a>




More posts of this category

Four reasons why I dislike Blazor as a React developer

After six months of working with Blazor, this is what i dislike about it


Set up a global state service in Blazor (Wasm)

Learn how to create a self coded Redux like functionality