In Razor view pages (.cshtml files), the @page directive can be used to add segments to a page’s default route. Use this feature by typing a string after @page.
For example, imagine the below code is from About.cshtml. Instead of /About, the new route would be /About/Me:
@page "Me"
@page "segment"
In Razor view pages (.cshtml files), the @page directive can be used to add parameters to a page’s route.
{ } after @page.int or alpha, can be added using colons :.?.Imagine the below code is from Book.cshtml. Instead of /Book, the new route could be /Book/0 or Book/1 or Book/2 etc.:
@page "{id:int}"
Imagine the below code is from House.cshtml. The new route could be /House or House/small or House/big etc.:
@page "{size?}"
Imagine the below code is from Song.cshtml. Instead of /Song, the new route would be /Song or Song/0 or Song/1 etc.:
@page "{song:int?}"
@page {param}
The asp-route-{value} attribute is used in <a> elements to add additional information to a URL route.
{value} typically matches a property in a page model.If the above <a> tag is in a .cshtml file, it would be rendered as this HTML:
<a href="localhost:8000/About?name=Joanne">About Joanne</a>
However, if the About page has a route parameter, like @page {name}, then the same tag would be rendered as this HTML:
<a href="localhost:8000/About/Joanne">About Joanne</a>
<a asp-page="About" asp-route-name="Joanne">About Joanne</a>
In ASP.NET Razor Pages, route parameters can be constrained to specific types using a colon followed by constraints like :int or :alpha. This helps ensure valid values are passed to your pages, enhancing security and functionality.
// Here is an example of using route constraints in Razor Pages:@page "/customer/{id:int}"public class CustomerModel : PageModel{public IActionResult OnGet(int id){// The id parameter is constrained to integers// Write logic here e.g., fetching the customer by idreturn Page();}}
In ASP.NET Razor Pages, use a question mark ? after a route parameter to make it optional. For example, /users/{id?} means the id parameter can be omitted, allowing flexibility in URL construction.
@page "/users/{id?}"@functions {public void OnGet(int? id){if (id.HasValue){// Logic if 'id' is providedConsole.WriteLine($"User ID: {id}");}else{// Logic if 'id' is missingConsole.WriteLine("ID not provided.");}}}