Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly typed route in @page directive in Razor Pages

On a ASP.NET Core Razor Page we can do this to change the default folder-based route:

@page "/xxx/yyy"

but trying to do this with a strongly typed property in some class Constants.Routes does not work

public const string Myroute = "/mysuperroute"; 

and

@page @Constants.Routes.Myroute

I am getting an error at compile time The 'page' directive expects a string surrounded by double quotes.

Is there a way around this? I would like to avoid route duplication through the options e.g. https://docs.microsoft.com/en-us/aspnet/core/razor-pages/razor-pages-conventions?view=aspnetcore-2.2#configure-a-page-route Thanks

like image 996
Octopus Avatar asked Mar 01 '19 09:03

Octopus


People also ask

What can the @page directive do in a Razor page?

@page makes the file into an MVC action, which means that it handles requests directly, without going through a controller. @page must be the first Razor directive on a page. @page affects the behavior of other Razor constructs. Razor Pages file names have a .

How do I navigate from one Razor to another page?

1 Answer. Show activity on this post. To solve my problem I used the asp-page attribute with Razor Pages and set an anchor tag's href attribute value to the specific page. I wrapped the anchor tag element in the button element and was able to navigate to the specified page when the button was clicked.

Which keyword of Razor syntax is used to render the view content in the layout page as body content?

The @section directive is used in conjunction with MVC and Razor Pages layouts to enable views or pages to render content in different parts of the HTML page.

What is difference between MVC and Razor pages?

Razor Page is similar to the HTML page but it loads data easily. A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself.


2 Answers

Little late to the party, but I had the same issue and found the RouteAttribute which associates the component with a given route template.

So you can do the following in your razor component and have it available under {host}:{port}/test:

@attribute [Microsoft.AspNetCore.Components.RouteAttribute(Href)]


@code {
  public const string Href = "test";
}

In a NavLink you can now do this:

<NavLink class="nav-link" href="@TestComponent.Href">
    Test Entry
</NavLink>

Source

like image 66
Radall Avatar answered Sep 23 '22 02:09

Radall


I don't know if a .NET core 3.1 thing, but RouteAttribute didn't work for RazorPages.

@page
@attribute [Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadata("RouteTemplate", MyRoutes.QualificationQueue)]
like image 25
BillRob Avatar answered Sep 26 '22 02:09

BillRob