Reputation: 1459
basically i have a problem, i want to make one default action in multiple controllers and use multiple optional parameters with my custom url as below:
www.mydomain.com/{controller name}/{v1}/{v2}/{v3}/{v4}
and also do not want action name in url. I have this routing in routeconfig.cs
routes.MapRoute(
name: "Blog",
url: "{controller}/{v1}/{v2}/{v3}/{v4}",
defaults: new
{
controller = "Blog",
action = "searchBlog",
v1 = UrlParameter.Optional,
v2 = UrlParameter.Optional,
v3 = UrlParameter.Optional,
v4 = UrlParameter.Optional
});
routes.MapRoute(
name: "Forum",
url: "{controller}/{v1}/{v2}/{v3}/{v4}",
defaults: new
{
controller = "Forum",
action = "searchForum",
v1 = UrlParameter.Optional,
v2 = UrlParameter.Optional,
v3 = UrlParameter.Optional,
v4 = UrlParameter.Optional
});
action in BlogController
public ActionResult searchBlog(string v1=null,string v2 = null, string v3 = null, string v4 = null)
{
// use optional parameters here
return View("Index");
}
action in ForumController
public ActionResult searchForum(string v1=null,string v2 = null, string v3 = null, string v4 = null)
{
// use optional parameters here
return View("Index");
}
my actions hit with 0, 3 and 4 parameters, but can not hit when pass 1 or 2 parameters.
e.g
www.mydomain.com/{controller name}/{v1}/{v2}
www.mydomain.com/{controller name}/{v1}
please help me / guide me, what is right way to use routing in MVC as i mentioned my requirements. i appreciate your valuable time. thanks in advance.
Upvotes: 3
Views: 1499
Reputation: 2577
You have to set the route configuration like this by fixing your route for each of your controllers otherwise the default route configuration will be called for that kind of scenario as you mentioned above and the route will become like this.
www.mydomain.com/blog/{v1}/{v2}/{v3}/{v4}
This route will work only for blog controller as we have fixed our route in this configuration.
routes.MapRoute(
name: "Blog",
url: "blog/{v1}/{v2}/{v3}/{v4}",
defaults: new
{
controller = "Blog",
action = "searchBlog",
v1 = UrlParameter.Optional,
v2 = UrlParameter.Optional,
v3 = UrlParameter.Optional,
v4 = UrlParameter.Optional
});
You have to manually do this for each of your controllers for the Forum as well and the resultant route will only work for forum controller.
www.mydomain.com/forum/{v1}/{v2}/{v3}/{v4}
routes.MapRoute(
name: "Forum",
url: "forum/{v1}/{v2}/{v3}/{v4}",
defaults: new
{
controller = "Forum",
action = "searchForum",
v1 = UrlParameter.Optional,
v2 = UrlParameter.Optional,
v3 = UrlParameter.Optional,
v4 = UrlParameter.Optional
});
Upvotes: 5