How can I check which route was used to call the page/component?

Viewed 202

Given a Razor page/component used in Blazor Server Side with

@page "/items/create"         // create route
@page "/items/edit/{id:long}" // edit route

In my code I need to know if the create route or edit route was used. How can I check this?

I am already aware of NavigationManager.Uri but that's not really error proof, e.g. NavigationManager.Uri.Contains("edit") will also evaluate to true for http://localhost:123/items/create/?edit=faked_edit (so will claim that the edit route was used, though the create route was used).

2 Answers

I had to do something similar in my case and couldn't find a proper solution but the workaround to check the whole path worked for me. You can use the below example:

NavigationManager.Uri.Contains("/items/edit/")

Additionally, in one place I also checked if the id is not null or empty which will then be the edit page.

I solved this by creating a component MyEditor which includes the add and edit functionality.

// Edit.razor
<MyEditor EditMode="true" />

// Add.razor
<MyEditor EditMode="false" />

Then inside MyEditorI use the EditMode parameter instead of trying to figure out if it's add or edit via the NavigationManager.

Related