93

你好我想从 Mvc 控制器返回一个锚点

控制器名称= DefaultController;

public ActionResult MyAction(int id)
{
        return RedirectToAction("Index", "region")
}

因此,指向索引时的 url 是

http://localhost/Default/#region

以便

<a href=#region>the content should be focus here</a>

我不是在问您是否可以这样做:如何将锚标记添加到我的 URL?

4

4 回答 4

139

我发现这种方式:

public ActionResult MyAction(int id)
{
    return new RedirectResult(Url.Action("Index") + "#region");
}

您也可以使用这种详细的方式:

var url = UrlHelper.GenerateUrl(
    null,
    "Index",
    "DefaultController",
    null,
    null,
    "region",
    null,
    null,
    Url.RequestContext,
    false
);
return Redirect(url);

http://msdn.microsoft.com/en-us/library/ee703653.aspx

于 2012-05-21T18:22:29.000 回答
16

很好的答案gdoron。这是我使用的另一种方式(只是为了在此处添加可用的解决方案)。

return Redirect(String.Format("{0}#{1}", Url.RouteUrl(new { controller = "MyController", action = "Index" }), "anchor_hash");

显然,通过 gdoron 的回答,在这个简单的情况下,可以通过以下方式使这更清洁;

return new RedirectResult(Url.Action("Index") + "#anchor_hash");
于 2014-01-29T03:49:24.640 回答
14

点网核心的简单方法

public IActionResult MyAction(int id)
{
    return RedirectToAction("Index", "default", "region");
}

以上产生/default/index#region。第三个参数是在# 之后添加的片段。

Microsoft 文档 - ControllerBase

于 2018-09-13T14:10:39.980 回答
4

扩展 Squall 的答案:使用字符串插值使代码更清晰。它也适用于不同控制器上的操作。

return Redirect($"{Url.RouteUrl(new { controller = "MyController", action = "Index" })}#anchor");
于 2016-10-31T10:51:54.500 回答