Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a URL for ASP.NET MVC action, including hostname and port? [duplicate]

My current request is:

http://www.mofeng.com:4355/

I want display an action url in asp.net view layer, url is like this(full url, including http://protocol + hostname + port + controllerName + actionName):

http://www.mofeng.com:4355/controllerX/actionY

like image 947
paul cheung Avatar asked Aug 31 '13 20:08

paul cheung


People also ask

How do I map multiple URLs to the same action in MVC?

Yes, We can use multiple URLs to the same action with the use of a routing table. foreach(string url in urls)routes. MapRoute("RouteName-" + url, url, new { controller = "Page", action = "Index" });

How do you create a URL for a controller?

UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u. Action("About", "Home", null);


2 Answers

enter image description here

Url.Action("Action", "Controller", null, Request.Url.Scheme);

How to include the following in the Form Action attribute?

1. Protocol(http:// or https://)
2. HostName
3. QueryString
4. Port

@{
    var actionURL = Url.Action("Action", "Controller", 
                               FormMethod.Post, Request.Url.Scheme)  
                    + Request.Url.PathAndQuery;
}
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, 
                                                   new { @action = actionURL }))
{
}
like image 120
Imad Alazani Avatar answered Sep 28 '22 20:09

Imad Alazani


besides the default route:

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Application", action = "Index", id = UrlParameter.Optional }
        );

you may need to implement a new one :

        routes.MapRoute(
            name: "ControllerXActionYRoute",
            url: "controllerX/actionY",
            defaults: new { controller = "controllerX", action = "actionY" }
        );

and then you can use :

<div>@Url.Action("Action", "Controller", null, Request.Url.Scheme);</div>

*EDIT: *

to get the full url you must go to absolute.

<div>VirtualPathUtility.ToAbsolute(@Url.Action("Action", "Controller"));</div>
like image 41
Bart Calixto Avatar answered Sep 28 '22 20:09

Bart Calixto