asp.net-mvc 使用“RedirectToAction”从控制器重定向到哈希
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10690466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect to a hash from the controller using "RedirectToAction"
提问by hidden
Hello I want to return an anchor from Mvc Controller
你好,我想从 Mvc 控制器返回一个锚点
Controller name= DefaultController;
控制器名称= DefaultController;
public ActionResult MyAction(int id)
{
return RedirectToAction("Index", "region")
}
So that the url when directed to index is
这样当指向索引时的 url 是
http://localhost/Default/#region
So that
以便
<a href=#region>the content should be focus here</a>
I am not asking if you can do it like this: How can I add an anchor tag to my URL?
我不是在问您是否可以这样做:如何将锚标记添加到我的 URL?
回答by gdoron is supporting Monica
I found this way:
我找到了这种方式:
public ActionResult MyAction(int id)
{
return new RedirectResult(Url.Action("Index") + "#region");
}
You can also use this verbose way:
您还可以使用这种详细的方式:
var url = UrlHelper.GenerateUrl(
null,
"Index",
"DefaultController",
null,
null,
"region",
null,
null,
Url.RequestContext,
false
);
return Redirect(url);
回答by Squall
Great answer gdoron. Here's another way that I use (just to add to the available solutions here).
很好的答案 这是我使用的另一种方式(只是为了添加到此处的可用解决方案中)。
return Redirect(String.Format("{0}#{1}", Url.RouteUrl(new { controller = "MyController", action = "Index" }), "anchor_hash");
Obviously, with gdoron's answer this could be made a cleaner with the following in this simple case;
显然,在 gdoron 的回答下,在这个简单的情况下,可以使用以下内容进行清洁;
return new RedirectResult(Url.Action("Index") + "#anchor_hash");
回答by Dermot
A simple way in dot net core
dot net core中的一个简单方法
public IActionResult MyAction(int id)
{
return RedirectToAction("Index", "default", "region");
}
The above yields /default/index#region. The 3rd parameter is fragmentwhich it adds after a #.
以上产生/default/index#region。第三个参数是它在# 之后添加的片段。
回答by Jon T UK
To Expand on Squall's answer: Using string interpolation makes for cleaner code. It also works for actions on different controllers.
扩展 Squall 的答案:使用字符串插值可以使代码更简洁。它也适用于不同控制器上的操作。
return Redirect($"{Url.RouteUrl(new { controller = "MyController", action = "Index" })}#anchor");

