Search code examples
asp.net-mvchtml.actionlink

How add #id to Html.ActionLink


How generate link like <a href="/home/index#item">text</a> with:

return RedirectToAction()

@Html.ActionLink()

I need add #item for tab open on page load. Thanx.


Solution

  • Just use the proper overload of the ActionLink helper:

    @Html.ActionLink(
        linkText: "text", 
        actionName: "index", 
        controllerName: "home", 
        protocol: Request.Url.Scheme, 
        hostName: null, 
        fragment: "item", 
        routeValues: null, 
        htmlAttributes: null
    )
    

    or a shortcut if you will:

    @Html.ActionLink("text", "index", "home", Request.Url.Scheme, null, "item", null, null)
    

    and if you wanted to redirect to such an action you could use the GenerateUrl method:

    public ActionResult SomeAction()
    {
        string url = UrlHelper.GenerateUrl(
            routeName: null,
            actionName: "index",
            controllerName: "home",
            protocol: null,
            hostName: null,
            fragment: "item",
            routeValues: new RouteValueDictionary(),
            routeCollection: Url.RouteCollection,
            requestContext: Url.RequestContext,
            includeImplicitMvcValues: false
        );
        return Redirect(url);
    }