How to add link parameter to asp tag helpers in ASP.NET Core
By Tan Lee Published on Dec 27, 2024 473
1. Using AnchorTagHelper with URL Parameters
To add a link parameter to an ASP.NET Core tag helper, such as the AnchorTagHelper
, use the asp-route-*
attributes. The AnchorTagHelper
generates an anchor (<a>
) tag, and by adding asp-route-{parameterName}
attributes, you can dynamically pass values for route variables in your HTML tags.
For example, asp-route-id="5"
would pass an id
parameter with a value of 5
to the route.
1 |
< a asp-controller = "Product" asp-action = "GetProduct" asp-route-id = "5" > ProductName</ a > |
This generates a URL like /Product/GetProduct/5
, where id
is the parameter and 5
is its value.
2. Using Query String Parameters
If you want to add query string parameters (e.g., ?param=value
), you can use the asp-route-*
attribute with the route and append the query parameters.
1 |
< a asp-controller = "Home" asp-action = "Search" asp-route-query = "test" >Search</ a > |
This would generate a URL like /Home/Search?query=test
.
3. Combining Route Parameters and Query String Parameters
You can combine both route parameters and query string parameters in the same link:
1 |
< a asp-controller = "Product" asp-action = "Details" asp-route-id = "10" asp-route-category = "electronics" >Product Details</ a > |
This will generate a URL like /Product/Details/10?category=electronics
.
4. Dynamically Set Link Parameters
If you want to dynamically set a parameter, you can use a variable or model property:
1 |
< a asp-controller = "Product" asp-action = "Details" asp-route-id = "@Model.ProductId" asp-route-category = "@Model.Category" >Product Details</ a > |
5. Using asp-area with Route Parameters
If you are using areas in your ASP.NET Core, you can also specify the area along with route parameters:
1 |
< a asp-area = "Admin" asp-controller = "Product" asp-action = "Edit" asp-route-id = "123" >Edit Product</ a > |
This generates a link like /Admin/Product/Edit/123
.
- How to Initialize TagHelpers in ASP.NET Core with Shared Data
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core