URL parameters and stylesheets in Blazor .NET 8

2 min read 04-10-2024
URL parameters and stylesheets in Blazor .NET 8


Dynamic Styling in Blazor .NET 8: Using URL Parameters for Tailored Looks

Blazor .NET 8 is a powerful framework for building interactive web applications. But sometimes you need to go beyond static styling and create a user experience that adapts to specific situations. This is where the combination of URL parameters and CSS comes in handy.

The Scenario: Personalized Themes

Let's imagine you're building a website that allows users to choose their preferred theme. A simple approach is to use URL parameters to store the user's theme preference, and then dynamically load different stylesheets based on that parameter.

Here's a basic example using Blazor:

@page "/theme"
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.WebUtilities

<h1>Choose Your Theme</h1>

<ul>
    <li><a href="?theme=light">Light Theme</a></li>
    <li><a href="?theme=dark">Dark Theme</a></li>
</ul>

@code {
    [Parameter]
    public string Theme { get; set; } = "light"; // Default to light theme

    protected override void OnInitialized()
    {
        base.OnInitialized();

        // Get theme parameter from the URL
        var queryParams = QueryHelpers.ParseQuery(NavigationManager.Uri);
        if (queryParams.TryGetValue("theme", out var themeValue))
        {
            Theme = themeValue;
        }
    }
}

This code creates two links, allowing users to select either a light or dark theme. The OnInitialized method retrieves the theme parameter from the URL, and the Theme property is used to determine which stylesheet to load.

Applying the Dynamic Styles

Now, let's create the CSS files:

  • Light Theme (light.css):

    body {
        background-color: #f0f0f0;
        color: #333;
    }
    
  • Dark Theme (dark.css):

    body {
        background-color: #333;
        color: #f0f0f0;
    }
    

To dynamically load the chosen stylesheet, you can use a <link> tag in your _Host.cshtml file:

<link href="~/css/light.css" rel="stylesheet" />
<link href="~/css/dark.css" rel="stylesheet" id="dynamic-theme" disabled />

<script>
    window.addEventListener('load', () => {
        const themeParam = new URLSearchParams(window.location.search).get('theme');
        const dynamicThemeLink = document.getElementById('dynamic-theme');
        if (themeParam === 'dark') {
            dynamicThemeLink.disabled = false;
        }
    });
</script>

This code includes both stylesheets, but only the dark.css stylesheet is initially disabled. The JavaScript code then reads the theme parameter from the URL and enables the appropriate stylesheet.

Advantages and Considerations

Using URL parameters for dynamic styling offers several advantages:

  • Flexibility: Easily change the theme without recompiling your application.
  • SEO Friendliness: Search engines can easily index different versions of your website based on the URL parameters.
  • User Control: Empower users to personalize their experience.

However, there are some considerations:

  • Complexity: Managing multiple stylesheets can become complex for larger applications.
  • Caching: Be mindful of browser caching and how it affects the dynamic loading of stylesheets.
  • User Experience: Ensure smooth transitions between different themes to avoid jarring user experience.

Going Beyond Simple Themes

This technique is not limited to just themes. You can use URL parameters to change other aspects of your website's appearance, such as:

  • Color schemes: Let users choose their preferred color palette.
  • Font styles: Allow users to select different fonts for text.
  • Layout variations: Offer alternative layouts based on user preferences or screen size.

By creatively using URL parameters, you can create a truly dynamic and engaging user experience in your Blazor applications.

Additional Resources

Remember, the possibilities are endless! Experiment and see how you can leverage URL parameters to enhance your Blazor applications.