Reputation: 2100
In my MVC4 project I have an url http://domain.com/{controller}/{action}/.
To determine what page user visits and and get current active menuitem I use url path like this HttpContext.Request.Url.AbsolutePath.ToLower()
However in some cases paths are /{controller}/{action}/{id} etc. which are actually /{controller}/{action}/?{id}=value.
How can I get /{controller}/{action}/ without parameters if they are overridden by routing rules?
Thank you.
Upvotes: 2
Views: 5539
Reputation: 1689
How about adding one new route before your current route which will be like this.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
new route will be like this -
routes.MapRoute(
name: "**Withoutparam**",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
Please note that you need to add this route before your current route in RouteConfig.cs. This is because MVC starts searching routes in RouteConfig file from top to bottom. As soon as it finds any matching route it will stop searching further. So for your problem when there will be route without param it will pick "Withoutparam" route.
As I can understand from your comment below. You need url without id in every condition. If it's so, then I think you can do this: -
var url = new StringBuilder();
string[] partOfUrl = HttpContext.Request.Url.AbsolutePath.ToLower().split('/');
for(int count = 0; count< (partOfUrl.Length - 1); count++)
{
url.Append(partOfLength[count] + "/")
}
use url.ToString() as url which you want.
Upvotes: 0
Reputation: 11095
Are you only interested in the controller and action names?
If so, use the RouteData property of the controller.
You can use it like this:
public ActionResult Index()
{
var controller = this.RouteData.Values["controller"];
var action = this.RouteData.Values["action"];
}
Upvotes: 3