Razor Pages: Dynamic Routing Parameter Name

Raymond Tang Raymond Tang 0 2117 1.29 index 12/30/2020

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>

infoAll routing parameter values need to be string type as asp-all-route-data itself is IDictionary<string,string>. All the additional routing parameters that are not defined in routing conventions will become query string.

asp.net asp.net-core

Join the Discussion

View or add your thoughts below

Comments