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?

2

4 Answers 4

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

4
  • 2
    You are a genious mate! Here what I ended doing: return new RedirectResult(Url.Action("Index",new{ PKMvrEmployeeId = MvrId }) + "#region");
    – hidden
    May 21, 2012 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 8, 2013 at 2:55
  • 2
    In MVC 5, when using RedirectToAction it appears to escape the # to a %23. Is no one else experiencing this? Oct 20, 2017 at 1:04
  • For me, it's going back up again when I use the same method. May 5, 2020 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");
1
  • The first option works well if your action is in a different controller. Dec 16, 2015 at 20:14
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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.