2012-04-24 51 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