You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core的OnPost方法中重定向到Razor页面指定锚点?

How to Redirect to a Razor Page with an Anchor Target

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:23:12