Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the URL of the Action without parameters in ASP.NET MVC

I have a ASP.NET MVC Web application that runs in a virtual directory on IIS. In the application, I have an Action which takes a parameter named Id.

public class MyController : MyBaseController 
{
    public ActionResult MyAction(int id)
    {
        return View(id);
    }
}

When I call the Action with the parameter 123 the resulting URL is like this:

http://mywebsite.net/MyProject/MyController/MyAction/123

In the base controller, how do I elegantly find the URL of the Action without any parameters? The string I'm trying to get is: /MyProject/MyController/MyAction

There are other questions asked about this but they do not cover these cases. For example Request.Url.GetLeftPart still gives me the Id.

like image 675
Hüseyin Yağlı Avatar asked Jul 17 '16 21:07

Hüseyin Yağlı


1 Answers

@trashr0x's answer solves the biggest part of the problem, but misses the MyProject part and there is no need for a dictionary to construct the asked string. here is a simple solution:

var result = string.Join("/", new []{ 
    Request.ApplicationPath, 
    RouteData.Values["controller"], 
    RouteData.Values["action"] 
});
like image 54
burkay Avatar answered Sep 19 '22 21:09

burkay