Redirect to a Razor page at a specific location in an OnPost

Viewed 1122

I have an OnPost function of the form

public IActionResult OnPost()
{
    //Do some stuff

    return RedirectToPage("/Forms/Strategy");
}

This works properly and the RedirectToPage opens the Razor page at the top. However, I would prefer the Redirect to open the Forms/Strategy page with a specific anchor point at the top of the browser window. That anchor is:

<h3><a id="RedirectTarget">Redirect Target</a></h3>

I have tried using a RedirectToPage of the form:

return RedirectToPage("/Forms/Strategy#RedirectTarget");

However, this results in an error:

InvalidOperationException: No page named '/Forms/Strategy#returnstable' matches the supplied values.

I assume I am incorrectly structuring the URL for the RedirectToPage.

1 Answers

You can specify the fragment for the generated URL using an overload of RedirectToPage. Here's an example:

return RedirectToPage("/Forms/Strategy", null, "RedirectTarget");

The null argument above populates the pageHandler parameter, which just uses the default page handler.

Although /Forms/Strategy looks like a URL, it actually represents the page name, as a path that's relative to the Pages directory. When you attempt to use /Forms/Strategy#RedirectTarget as the page name, the route-generation process rightly fails to find a match.

Related