Razor Pages: Dynamic Routing Parameter Name
In ASP.NET Razor pages, routing component it used to match request URL to a defined routing conventions and then the correspondent page handler will be used to handle the HTTP request and to provide response. Razor pages provide tag helpers to easily create a link based on routing parameters.
Routing tag example
The following code snippet creates a hyper link based on page model name and routing parameters:
<a asp-area="" asp-page="Article" asp-id="1">Article 1</a>
Assuming the page routing contention is like the following:
options.Conventions.AddPageRoute("/Article", "/article/{id:int}");
The generated hyperlink will be:
<a href="/article/1">Article 1</a>
If the routing convention is like this:
options.Conventions.AddPageRoute("/Article", "/article");
Then the generated hyperlink will be '/article?id=1'.
Dynamic routing parameters
In some cases, you may want to dynamically pass routing parameters. For example, generate different routing values for different page type:
/articles/1 /threads/2
Or in some scenario, the routing parameters can be dynamic. In the above example, routing parameter id is hardcoded as asp-id="1". If the parameter value is from a constant variable or other variables or from a database column, you can use asp-route-all-values tag helper attribute:
@{ var idKey = "id"; var parms = new Dictionary<string, string> { { idKey, "1" }
}; } <a asp-area="" asp-page="Article" asp-all-route-data="parms">Article 1</a>