Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - how to get a full path to an action

Inside of a View can I get a full route information to an action?

If I have an action called DoThis in a controller MyController. Can I get to a path of "/MyController/DoThis/"?

like image 386
dev.e.loper Avatar asked Jul 21 '11 22:07

dev.e.loper


2 Answers

You mean like using the Action method on the Url helper:

<%= Url.Action("DoThis", "MyController") %> 

or in Razor:

@Url.Action("DoThis", "MyController") 

which will give you a relative url (/MyController/DoThis).

And if you wanted to get an absolute url (http://localhost:8385/MyController/DoThis):

<%= Url.Action("DoThis", "MyController", null, Request.Url.Scheme, null) %> 
like image 159
Darin Dimitrov Avatar answered Oct 13 '22 21:10

Darin Dimitrov


Some days ago, I wrote a blog post about that very topic (see How to build absolute action URLs using the UrlHelper class). As Darin Dimitrov mentioned: UrlHelper.Action will generate absolute URLs if the protocol parameter is specified explicitly.

However, I suggest to write a custom extension method for the sake of readability:

/// <summary> /// Generates a fully qualified URL to an action method by using /// the specified action name, controller name and route values. /// </summary> /// <param name="url">The URL helper.</param> /// <param name="actionName">The name of the action method.</param> /// <param name="controllerName">The name of the controller.</param> /// <param name="routeValues">The route values.</param> /// <returns>The absolute URL.</returns> public static string AbsoluteAction(this UrlHelper url,     string actionName, string controllerName, object routeValues = null) {     string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;      return url.Action(actionName, controllerName, routeValues, scheme); } 

The method can then be called like this: @Url.AbsoluteAction("SomeAction", "SomeController")

like image 28
Marius Schulz Avatar answered Oct 13 '22 21:10

Marius Schulz