Michael Bradvica joined Saxony Partners in 2020 as a Software Engineer on our app dev team. Previously, he has worked as a Full-Stack .NET Developer for technology services firms. You can read more of his thought leadership at MichaelBradvica.com – from which the blog post below has been adapted.

Routing with Variables in Blazor: Step-by-Step

Routing to components in Blazor is easy when leveraging variables. This can be a cleaner alternative to using raw strings throughout.

The example below uses the default Counter component included whenever a new Blazor project is created. The only requirement is a class that contains constant strings to use for our routes:

“`csharp

    public static class PageRoutes

    {

        public const string Counter = “counter”;

        public const string CounterRoute = “/counter”;

    }

“`

Note: Constant interpolated strings are in a preview stage to cut down on redundancies.

You can use routes with parameters as well:

“`csharp

    public static class PageRoutes

    {

        public const string MyParams = “/myparams/{id:int}”;

    }

“`

You can now update your NavLinks to the following:

“`html

<NavLink href=”@PageRoutes.Counter”>

“`

Your components will use the “@attribute” directive instead of “@page” now.

“`csharp

@page “/counter”

“`

becomes…

“`csharp

@attribute [Route(PageRoutes.CounterRoute)]

“`

Using variables for routing in Blazor is a small change that increases reusability and removes naked strings.

Making Digital Practical with Saxony Partners

Technology and digital strategy can be complicated, but our goal at Saxony Partners is simple: Make Digital Practical.

Saxony Partners will meet you where you are and help you get where you want to go. Our pragmatic approach helps ensure early success by leveraging proven technologies and practical solutions in a cost-effective way.

Our team of app dev experts, full-stack developers, and software engineers work with clients to optimize their technology investments and leverage that technology to meet and solve business needs and challenges.

If you or your company is looking for help with software development, reach out to us here.