ASP.Net MVC Tip: URL Anchor Tags

This is one of those features which should be baked into MVC by default, but isn't.

Actually, it is partially supported by MVC. This Codeplex answer details it:


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

will produce (assuming default routes):

[sourcecode language="html"] <a href="/Controller/Action/123#fragment">Link Text</a> [/sourcecode]

But what if you want the returned redirect of an ActionResult method to include the anchor tag. There is no RedirectAnchorTagResult to return.


That same answer does some voodoo to pull it off:

[sourcecode language="csharp"] 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); } [/sourcecode]


It is this that should be baked into MVC by default. Thats an awful lot of complexity to expose just for the sake of a simple anchor tag. So, yes, a RedirectAnchorTagResult would be a nice addition.


Thanks to Darin Dimitrov for providing the answer. Go ahead and upvote his answer.