Jush Stone
Jush Stone

Reputation: 99

Define a route with root-value and slug in Razor Pages

I want to create a link that has a root value and a slug value. Something like this:

http://localhost:5001/Page/rootValue?slug=1

How can I do that?

The tag I wrote is as follows:

<a asp-page="./ProductCategory" asp-route-id="@category.Slug" asp-route-page="1">@category.Name</a>

I want the following output to be obtained:

http://localhost:5001/productCategory/cars?page=1

But in practice, the slug value is not recieved.

Other things I did was to get the id rootvalue in the destination page:

@page {id}

and in the destination page-model, get URL values:

OnGet(string id, int page)

But when I run the program, the slug value (page) is zero and the page does not load.

Do I have to enter something for routes in the StartUp.cs file? like the MapRoute method from MVC model, is there a similar method for Razor Pages?

Upvotes: 0

Views: 694

Answers (1)

Mike Brind
Mike Brind

Reputation: 30065

Route values that have the same name as route template parameters and are mapped to URL segments. Other route values are added to the URL as query string values.

In the following example, you have a parameter named category. This will appear as a segment:

@page "{category}"

The asp-route-category attribute specifies "rootValue as the category parameter value:

<a asp-page="SomePage" asp-route-category="rootValue" asp-route-slug="my-slug-value">Click</a>

The asp-route-slug attribute doesn't have a matching parameter so will be added as a query string value resulting in

SomePage/rootValue?slug=my-slug-value

You can use the BindProperty attribute to bind the URL values to public properties on the PageModel:

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

More from my site:

Upvotes: 1

Related Questions