如何在ASP.NET Core的OnPost方法中重定向到Razor页面指定锚点?
Got it, let's sort out that anchor redirect issue you're facing. The problem with your initial approach is that RedirectToPage() treats the entire string (including the #RedirectTarget part) as the page name, which is why it throws that "no page matches" error—Razor Pages doesn't recognize the anchor as part of the page path.
Here are two reliable ways to fix this:
1. Use the RedirectToPage overload with a fragment parameter
This is the cleanest and recommended approach, since it leverages Razor Pages' built-in URL generation:
public IActionResult OnPost() { // Your existing operation code here return RedirectToPage("/Forms/Strategy", fragment: "RedirectTarget"); }
If you need to pass route values to the target page along with the anchor, you can use this overload:
return RedirectToPage("/Forms/Strategy", new { /* add route params here, e.g., id = 5 */ }, fragment: "RedirectTarget");
This will automatically construct the correct URL with the anchor appended, like /Forms/Strategy#RedirectTarget, and the browser will jump straight to your <a id="RedirectTarget"> element.
2. Manually build the URL with Url.Page()
If you prefer a more explicit approach, you can generate the base page URL first and then append the anchor yourself:
public IActionResult OnPost() { // Your existing operation code here var targetUrl = Url.Page("/Forms/Strategy") + "#RedirectTarget"; return Redirect(targetUrl); }
This works because Url.Page() returns the valid URL path for the specified page, and adding the anchor manually ensures it's correctly attached to the end.
Either method will resolve the error and get your redirect pointing to the right anchor position.
内容的提问来源于stack exchange,提问作者Dennis

