Search code examples
razorblazorblazor-webassembly

How do you link to other razor pages and include a query string parameter in Blazor WASM?


I've got a Blazor WASM app. It has two razor pages:

Documentation.razor:

@page "/documentation"

ViewRecord.razor:

@page "/documentation/ViewRecord"

I have a DocumentationController too.

I want to create a few hyperlinks within the Documentation razor page that have hyperlinks in this format:

/Documentation/ViewRecord?recordtype=randomWord1
/Documentation/ViewRecord?recordtype=randomWord2
/Documentation/ViewRecord?recordtype=randomWord3

Is there a cleaner way to do this, similar to using ActionLinks, instead of having to do something like this:

<a href="Documentation/ViewRecord?recordtype=@word1">link1</a>
<a href="Documentation/ViewRecord?recordtype=@word2">link2</a>
<a href="Documentation/ViewRecord?recordtype=@word3">link3</a>

Solution

  • This is the beauty of Blazor and Razor Components, if you find you want to something, you can create a re-usable component for it yourself. Complete flexibility. Say for instance we have the following component:

    UrlBuilder.razor

    @if (!string.IsNullOrEmpty(FullUrl))
    {
        <a href="@FullUrl" class="link">@LinkDesc</a>
    }
    
    @code
    {
        [Parameter]
        public string LinkDesc { get; set; }
        [Parameter]
        public string Controller { get; set; }
        [Parameter]
        public string Action { get; set; }
        [Parameter]
        public string UrlParameter { get; set; }
        private string FullUrl { get; set; }
    
        protected override void OnInitialized()
        {
            FullUrl = $"{Controller}/{Action}?{UrlParameter}";
        }
    
    }
    

    You can then access that component anywhere through your application like so:

    <UrlBuilder LinkDesc="link 1" Controller="Documentation" Action="ViewRecord" UrlParameter="@word3" />
    

    Renders

    Is that any easier than creating a a href manually? Absolutely not, however, you could customize it to your delight.