2012-04-24 54 views
5

可能重複:
How to I find the absolute url of an action in ASP.NET MVC?
Asp MVC Action link absolute url在MVC中生成完整的URL?

嗨,

有沒有一種簡單的方法來生成特定動作的完整網址?我試過這個:

urlHelper.Action("Action", "Controller") 

但是這確實會產生一個「\」。

BestRegards

編輯1:我已經試過這樣:

urlHelper.Action("List", "Ad", null, "http"); 

但它只返回:本地主機:16055。我期待像localhost:16055/Ad/List?

+0

這是在一個視圖,或在控制器代碼的上下文? – Tejs 2012-04-24 15:23:42

+0

只需預先安裝主機/協議信息? – 2012-04-24 15:23:54

回答

15

使用Html.ActionLink(「鏈接名稱」,「行動」,「控制器」)

要生成一個完整的鏈路中使用:

@Html.ActionLink("Link Title", "Action", "Controller", "http", "www.mysampledomain.com", 
       "_blank", new {id = paramValue}, new { @class="someClass" }) 

這是所有參數的擴展超載你可以指定。看看這個MSDN文章http://msdn.microsoft.com/en-us/library/dd492938.aspx

在從控制器生成使用此代碼:

var url = UrlHelper.GenerateUrl(null, "MyAction", "MyController", "http", "www.mydomain.com", String.Empty, null, RouteTable.Routes, this.ControllerContext.RequestContext, false); 

url變量將包含URL的字符串表示。您可以在ViewBag其存儲這樣的:

ViewBag.MyUrl = UrlHelper.GenerateUrl(null, "MyAction", "MyController", "http", "www.mydomain.com", String.Empty, null, RouteTable.Routes, 
             this.ControllerContext.RequestContext, false); 

從視圖中稱其爲:

@ViewBag.MyUrl 

這應該是它。

+0

如何從控制器操作執行此操作? – Banshee 2012-04-24 15:27:50

+2

Html.ActionLink生成一個鏈接。如果您想要完整的URL,請使用Url幫助程序Url.Action。該方法的重載之一允許您指定架構,並在此過程中生成完全限定的URL,如http:// localhost:1234/controller/action – 2012-04-24 15:29:25

+0

不一定。 Html.ActionLink有一個重載,也可以創建一個完整的鏈接。 – 2012-04-24 15:32:26

0

Url.action生成一個url相對。要生成一個網址絕對你可以看看這個:How do I find the absolute url of an action in ASP.NET MVC?

+0

我試過這個:urlHelper.Action(「List」,「Ad」,null,「http」);但它只返回:http:// localhost:16055 /。我期待像http:// localhost:16055/Ad/List? – Banshee 2012-04-24 16:32:41