Redirect to a hash from the controller using "RedirectToAction"

asp.net Mvcasp.net Mvc-3asp.net Mvc-4

asp.net Mvc Problem Overview


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: https://stackoverflow.com/questions/7904835/how-can-i-add-an-anchor-tag-to-my-url

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

Solution 2 - asp.net Mvc

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

Solution 3 - asp.net Mvc

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

Solution 4 - asp.net Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhiddenView Question on Stackoverflow
Solution 1 - asp.net Mvcgdoron is supporting MonicaView Answer on Stackoverflow
Solution 2 - asp.net MvcSquallView Answer on Stackoverflow
Solution 3 - asp.net MvcDermotView Answer on Stackoverflow
Solution 4 - asp.net MvcJon T UKView Answer on Stackoverflow