C# > Blazor and Web Development > Blazor Components > Routing in Blazor
Routing with Parameters
This example demonstrates how to define routes with parameters in Blazor. It shows how to extract parameter values from the URL and use them within your component. This is essential for scenarios where you need to display dynamic content based on user input or data IDs.
Component Definition with Parameterized Route
This code defines a Blazor component that accepts a route parameter named ProductId
. The @page
directive specifies the route /product/{ProductId:int}
. The {ProductId:int}
part indicates that ProductId
is a parameter and that it should be parsed as an integer. The [Parameter]
attribute on the ProductId
property tells Blazor to bind the route parameter's value to this property. The value of the ProductId
property is then displayed in the UI.
@page "/product/{ProductId:int}"
<h3>Product Details</h3>
<p>Product ID: @ProductId</p>
@code {
[Parameter]
public int ProductId { get; set; }
}
Explanation of Route Parameters and Constraints
Route parameters are enclosed in curly braces {}
in the @page
directive. You can add constraints to route parameters by adding a colon :
followed by the constraint name (e.g., :int
, :guid
, :bool
). Constraints ensure that the parameter value matches the expected type, preventing errors and improving security. If a constraint is not met, the route will not match, and Blazor will look for another matching route.
How to Navigate to This Component
To navigate to this component, you would use a URL like /product/123
, where 123
is the value for the ProductId
parameter. You can also use the <NavLink>
component to create a hyperlink to this route, constructing the URL dynamically:
<NavLink href="/product/@productId">View Product</NavLink>
@code {
private int productId = 123; // Example product ID
}
Real-Life Use Case
Consider a blog application. You might have a route /blog/{PostId}
to display individual blog posts. The PostId
parameter would be used to retrieve the correct post from a database and display its content.
Best Practices
/search/{searchTerm?}
). Make sure you handle the case where the optional parameter is not provided.
Interview Tip
Be prepared to discuss the different types of route constraints available in Blazor (e.g., :int
, :guid
, :bool
, :datetime
) and when you would use each one. Also, understand how to handle optional route parameters.
FAQ
-
What happens if I navigate to /product/abc (where 'abc' is not an integer)?
Because the ProductId parameter has a constraint of `:int`, Blazor's router won't match this component to the URL `/product/abc` and try to render the component. If no other route matches the provided URL a 404 page will be returned. -
Can I have multiple parameters in a single route?
Yes, you can have multiple parameters in a route (e.g.,/product/{CategoryId:int}/{ProductId:int}
).