Home > Software engineering >  Do variable check only once in blazor
Do variable check only once in blazor

Time:12-21

I have several razor pages I want to do checks on using the current URL value.

They currently all have in their @code{} block URLs like:

Razor Page 1: MyNavigationManager.NavigateTo("sample_domain/sub_page_1?i="   variable, forceLoad: true);
Razor Page 2: MyNavigationManager.NavigateTo("sample_domain/sub_page_2?i="   variable, forceLoad: true); 
Razor Page 3: MyNavigationManager.NavigateTo("sample_domain/sub_page_3?i="   variable, forceLoad: true);

I would like to remove the sample_domain/ part if the URL has localhost in it.

So I have seen here that I can get the current urls by Injecting before using it on .razor pages @inject NavigationManager MyNavigationManager and using MyNavigationManager.Uri to get the url.

Now I implemented it doing the following in each of the razor pages code block:

//check if the url has localhost
string domain_url = MyNavigationManager.Uri.ToString().Contains("localhost") ? "" : "/sample_domain";
MyNavigationManager.NavigateTo($"{domain_url}/sub_page_1?i="   variable, forceLoad: true);

But now I only want to do the check once, and set the variable there, e.g. the domain_url. Then use that variable in the different razor pages without explicitly checking and setting it in each page. Maybe something like a global variable? session? But not sure how to go about that? Thanks.

CodePudding user response:

You can call a method in a service to do that for you. For example, create a service MyService.cs, and have a method like GetUrl

public string GetUrl(string nav_url)
{
    return nav_url.ToString().Contains("localhost") ? "" : "/sample_domain";
}

Inject the service @inject MyService MService in _Imports.razor, then call the method like:

MyNavigationManager.NavigateTo($"{MService.GetUrl(MyNavigationManager.Uri)}/sub_page_1?i="   variable, forceLoad: true);
  • Related