Route Parameter In Razor Pages Sagar Jaybhay

In this article we will understand Route Parameter In Razor Pages By Sagar Jaybhay.

Route Parameter:

Another way to pass value from is route template. If you see the above image you have seen that the id parameter is passed as a query string parameter. But we want to pass as route template to do this we need to add below code in our Display template of Details .cshtml page.

@page "{id}"

By doing so our URL will become like below

Here are URL contains id but not as a QueryString parameter. If you want to make the id parameter as optional value then you need to add a Question mark after this like below.

@page " {id?}"

Now we want to change the route URL you can do so by using the route template right now in our application we go to details view and we want our URL like https://localhost:44316/employee/details/view/a101/  to achieve this modify route template like below and you can achieve this.

@page "view/{id}"

The output is shown in the below image. By doing so /view and /id is appended to default URL and URL looks like below

But this URL so long we want some custom URL like https://localhost:44316/employee/view/a101/ To achieve this URL we need to modify route template like below

@page "/employee/view/{id}"

The output of this shown in below image and we can remove details name in URL

If you want to include as many parameters uses below syntax the name present in {} curly braces are route parameters.

@page "/employee/view/{id}/{name}"

Here keep in mind Model binder binds route parameter to id parameter in OnGet() method.

But if you want to access the Id parameter in the Display template you need to create a public property and assign value to it in the OnGet method.

Now this property we use in our Display Template so our output looks like below

So here we need to assign route parameter value to public property in OnGet() method why because by default route parameter support for OnPost()
the method only but we want to access for OnGet() means get call also so we need to use below syntax for that and no need to assign value in OnGet() method. Code for this is written below

        [BindProperty(SupportsGet = true)]
        public string ID { get; set; }

The bind property attribute binds route parameter value to ID property in Page template public property. By default, BindProperty Bind value to this public property only for Post request so we pass SupportsGet flag to true to support for Get() call also.


Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts