0
votes

I have a JobPosts/Index page with multiple GET parameter bindings to allow filtering: let's take CityId and IsRemote for example. I don't want these to be passed as query string parameters, instead I want to use friendly routes for them. So I have defined these:

options.Conventions.AddPageRoute("/JobPosts/Index", "cities/{cityId}/jobs");
options.Conventions.AddPageRoute("/JobPosts/Index", "remote-jobs");
options.Conventions.AddPageRoute("/JobPosts/Index", "jobs");

The routes work just fine when I type them in the browser and the CityId one is bound properly, but two things are missing.

First, there is no way to specify a default value for my IsRemote param, which I want to set to true ONLY when using the remote-jobs URL.

And second, when trying to generate a URL like this:

<a asp-area="" asp-page="/JobPosts/Index" asp-route-cityId="@Model.CityId"></a>

I get the following URL:

https://localhost:44391/jobs?cityId=2265885

When what I actually expect is:

https://localhost:44391/cities/2265885/jobs

So it looks like the tag helper or the part responsible for constructing the URL doesn't look at all at the different routes to try and get a best match based on the list of parameters. Actually, it will always use the last page route defined for that page.

Nor do I have the option anywhere to specify a route name for the page route and then use asp-route to explicitly say which route I want.

Any ideas how to achieve that? Or if it's something that's on the roadmap for Razor Pages?

EDIT: Hardcoding the href is not an option. I want this to go through the proper routing services as there are other things to be done as well, like generating culture-specific URL for non-english users (eg. {cultureId}/cities/{cityId}/jobs - this is done through route conventions. Hardcoding the href would obviously bypass that.

1

1 Answers

0
votes

There is a easy way to set IsRemote default value.

public bool IsRemote { get; set; } = true;

This tag asp-page will link to Page /JobPosts/Index.csthml directly,

https://localhost:44391/JobPosts?cityId=2265885

= https://localhost:44391/JobPosts/Index?cityId=2265885

If you are looking forward the URL https://localhost:44391/jobs?cityId=2265885 you could try this a tag to request.

<a href="/cities/@Model.CityId/jobs">Go to JobPosts</a>

———————————————————————————————

Using a middleware to handle /remote-jobs

        app.Run(next => async context =>
        {
            if (context.Request.Path == "/remote-jobs")
            {
                return View with default IsRemote 
            }
        });