Sorry for asking a rather n00b question, I am rather new to ASP.NET MVC. My problem is as follows:
I want my site to handle a URL in the following way:
www.mysite.com/homepage/name
I want the above link to go to that user's profile. For simplicity the controller will be the Homepage controller with the Test action.
Meaning that the global.asax routing will be:
routes.MapRoute(
"test",
"homepage/{name}",
new { controller = "Homepage", action = "Test" }
);
Up until now the code works great (I have tested it and it routes ok).
But now my other functionality which I want is to enable:
www.mysite.com/homepage/action/id
To work as well.
The routing for this will be:
routes.MapRoute(
"Default",
"homepage/{action}/{id}",
new { controller = "Homepage", action = "Index", id = UrlParameter.Optional }
);
The problem is what happens when a user wants to omit the {id} for an action, the routing table detects that the action name is actually the {name} parameter.
Is there any way to first CHECK if an action exists. And only if it doesn't, then use it as a parameter for a different route.
Makes sense? if not I'll add some more details.
Thanks!
EDIT
So I've managed to solve this using the constraints regex I placed a regex defining a all the actions in my controller:
routes.MapRoute(
"homepage",
"homepage/{action}/{id}",
new { controller = "Homepage", action = "Index", id = UrlParameter.Optional },
new { action = "(action1|action2|action3)" }
);
And then the next rule:
routes.MapRoute(
"feed",
"homepage/{id}",
new { controller = "Homepage", action = "Test"}
);
I works ok, only it's hard to scale upon this. You need to remember to place every new action on the controller inside the string here. It's a huge opening for debug nightmares.
Thank you !
Since ASP.NET MVC selects the first route from the RouteTable that matches the current request, you should be able to fix this problem by changing the order of the routes in the Global.asax.
First this:
routes.MapRoute(
"Default",
"homepage/{action}/{id}",
new { controller = "Homepage", action = "Index", id = UrlParameter.Optional }
);
and then this:
routes.MapRoute(
"test",
"homepage/{name}",
new { controller = "Homepage", action = "Test" }
);
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With