Raymond Raymond / ASP.NET Core

Razor Pages: Dynamic Routing Parameter Name

event 2020-12-30 visibility 1,962 comment 0 insights toc
insights Stats

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:


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. 
More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts