2011-10-26 53 views
19

MVC 3.net我想添加一個錨到結束一個URL。如何將錨標記添加到我的網址?

我試圖包括一個錨查詢字符串,但哈希'#'變成%23或類似的URL中的。

有沒有辦法解決這個問題?

+1

http://stackoverflow.com/questions/10690466/redirect-to-a-hash-from-the-controller-using-redirecttoaction – hidden

回答

36

還有就是ActionLink幫手,它允許您指定片段的過載:

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

將產生(假設默認路由):

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

UPDATE:

,如果你想在控制器動作中執行重定向,你可以使用GenerateUrl方法:

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

不錯,不知道這一點。謝謝! –

+0

謝謝達林。在這種情況下,我正在使用重定向到操作來從控制器生成一個url,並且它只有6個重載不包含fragment。任何解決方案? – DevDave

+4

在這種情況下,您可以使用控制器中的[UrlHelper.GenerateUrl](http://msdn.microsoft.com/en-us/library/ee703653.aspx)方法,該方法允許您指定片段,然後重定向到產生的網址。我已更新我的帖子以提供示例。 –