94

Hello I want to return an anchor from Mvc Controller

Controller name= DefaultController;

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

So that the url when directed to index is

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?

Community
  • 1
  • 1
hidden
  • 3,216
  • 8
  • 47
  • 69
  • http://stackoverflow.com/questions/7904835/how-can-i-add-an-anchor-tag-to-my-url – DevDave Sep 11 '13 at 09:53
  • 1
    Possible duplicate of [ASP.Net MVC RedirectToAction with anchor](https://stackoverflow.com/questions/602788/asp-net-mvc-redirecttoaction-with-anchor) – GSerg Apr 18 '19 at 08:33

4 Answers4

141

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);

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

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 2
    You are a genious mate! Here what I ended doing: return new RedirectResult(Url.Action("Index",new{ PKMvrEmployeeId = MvrId }) + "#region"); – hidden May 21 '12 at 21:32
  • 1
    +1 for using RedirectResult instead of calling Redirect(..) method. In MVC under release and IIS6 you can end up with exceptions caused by redirecting because a request is perhaps already redirected, or part of a child action, or content is already sent. – Jaans Aug 08 '13 at 02:55
  • 2
    In MVC 5, when using RedirectToAction it appears to escape the # to a %23. Is no one else experiencing this? – jakejgordon Oct 20 '17 at 01:04
  • For me, it's going back up again when I use the same method. – Zeeshan Ahmad Khalil May 05 '20 at 16:10
16

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;

return new RedirectResult(Url.Action("Index") + "#anchor_hash");
Squall
  • 821
  • 8
  • 8
14

A simple way in dot net core

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

The above yields /default/index#region. The 3rd parameter is fragment which it adds after a #.

Microsoft docs - ControllerBase

Dermot
  • 324
  • 2
  • 6
5

To Expand on Squall's answer: Using string interpolation makes for cleaner code. It also works for actions on different controllers.

return Redirect($"{Url.RouteUrl(new { controller = "MyController", action = "Index" })}#anchor");
Jon T UK
  • 51
  • 1
  • 2