Vy Do
Vy Do

Reputation: 52586

How to implement idea Blazor global variable?

My real problem: I create help document for web-app, I can deploy it to other domain. In development environment, I use localhost, but in production, I use real sub-domain.

I have many pages likes this

<DxToolbar>
    <DxToolbarItem Text="New" Click="@OnAddNewClick" IconCssClass="grid-toolbar-new" />
    <DxToolbarItem Text="Edit" Click="@OnEditClick" IconCssClass="grid-toolbar-edit" Enabled="@Enabled" />
    <DxToolbarItem Text="Delete" Click="@OnDeleteClick" IconCssClass="grid-toolbar-delete" Enabled="@Enabled" />
    <DxToolbarItem Text="Filter" Click="@OnShowFilterRow" IconCssClass="grid-toolbar-filter-row" />
    <DxToolbarItem Text="Help" NavigateUrl="http://example.com/help/group1/feature001/" IconCssClass="grid-toolbar-document" target="_blank" />
    <DxDataGridColumnChooserToolbarItem Text="Choose columns" Tooltip="Choose columns" />
</DxToolbar>

In other pages

<DxToolbarItem Text="Help" NavigateUrl="http://example.com/help/group1/feature003/" IconCssClass="grid-toolbar-document" target="_blank" />

and

<DxToolbarItem Text="Help" NavigateUrl="http://example.com/help/group2/feature005/" IconCssClass="grid-toolbar-document" target="_blank" />

I want use something like

@base_help_url//help/group1/feature001/
@base_help_url//help/group1/feature003/
@base_help_url//help/group2/feature005/

and how/where to set @base_help_url?

How to implement this idea?

Upvotes: 1

Views: 2430

Answers (1)

Dennis VW
Dennis VW

Reputation: 3217

Step 1. Store the @base_help_url in an AppSettings file, then optionally configure it in an options class.

//AppSettings.Development.json
{
  "HelpUriBase": "..."
}

Step 2. Create an interface IHelpUri that exposes a method string GetBaseUri(); then implement the interface in a derived class.

public class HelpUri : IHelpUri
{
    private readonly string _helpUriBase;

    public HelpUri(IConfiguration configuration)
    {
        _helpUriBase = configuration.GetSection("HelpUriBase");
    }

    public string GetBaseUri => _helpUriBase;
}

Step 3. Create a (Blazor) component that wraps the DxToolbarItem component and has a [Parameter] string Path.

// HelpLink.razor
@inject IHelpUri HelpUri

<DxToolbarItem NavigateUrl="@Uri" />

@code {

  [Parameter] public string Path { get; set; }

  private string _helpUriBase;

  protected string Uri => $"{_helpUriBase}/{Path}"

  protected override async Task OnInitializedAsync()
  {
      _helpUriBase ??= HelpUri.GetBaseUri();
  }
  
}

Step 4. Use the HelpLink component instead of the DxToolbarItem component when creating help links.

<HelpLink Path="help/group1/feature001/" />
<HelpLink Path="help/group1/feature003/" />
<HelpLink Path="help/group2/feature005/" />

Upvotes: 2

Related Questions