How can I add an anchor tag to my URL?

走远了吗. 提交于 2019-12-17 18:51: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?


回答1:


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


来源:https://stackoverflow.com/questions/7904835/how-can-i-add-an-anchor-tag-to-my-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!