19

MVC 3.net I want to add an anchor to the end a url.

I tried to include an anchor query string but the hash '#' changes to %23 or something like that in the url.

Is there a way of working around this?

DevDave
  • 6,700
  • 12
  • 65
  • 99
  • 1
    http://stackoverflow.com/questions/10690466/redirect-to-a-hash-from-the-controller-using-redirecttoaction – hidden May 23 '12 at 16:59

1 Answers1

36

There is an overload of the ActionLink helper that allows you to specify the fragment:

@Html.ActionLink(
    "Link Text",           // linkText
    "Action",              // actionName
    "Controller",          // controllerName
    null,                  // protocol
    null,                  // hostName
    "fragment",            // fragment
    new { id = "123" },    // routeValues
    null                   // htmlAttributes
)

will produce (assuming default routes):

<a href="/Controller/Action/123#fragment">Link Text</a>

UPDATE:

and if you wanted to do this within a controller action performing a redirect you could use the GenerateUrl method:

public ActionResult Index()
{
    var url = UrlHelper.GenerateUrl(
        null,
        "Action",
        "Controller",
        null,
        null,
        "fragment",
        new RouteValueDictionary(new { id = "123" }),
        Url.RouteCollection,
        Url.RequestContext,
        false
    );
    return Redirect(url);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • thanks darin. in this case i am using redirect to action to generate a url from a controller, and it only has 6 overloads not including fragment. any solution to this? – DevDave Oct 26 '11 at 15:27
  • 4
    In this case you could use the [UrlHelper.GenerateUrl](http://msdn.microsoft.com/en-us/library/ee703653.aspx) method within your controller which allows you to specify a fragment and then redirect to the resulting url. I have updated my post to provide an example. – Darin Dimitrov Oct 26 '11 at 15:29
  • Plz see this solution: http://stackoverflow.com/questions/10690466/redirect-to-a-hash-from-the-controller-using-redirecttoaction – hidden Dec 18 '13 at 02:00