Nomi Ali Nomi Ali - 8 months ago 32
C# Question

URL Routing in MVC C#

I am defining my application URLs like

domainname.com/storecontroller/storeaction/storename


I want to rewrite like

domainname.com/storecontroller/storename


Actually, I need to skip storeaction from the url, I don't want to do it with querystring with "?" Is there anyway to do it by registering rout config path or any another way?

Answer

Yes. You can define action as a default parameter, and match for only specific controllers with a Regex constraint:

routes.MapRoute("<route name>", "{controller}/{storename}", 
     new 
     { 
         action = "storeaction" 
     },
     new
     {
         controller = "somecontroller1|somecontroller2|somecontroller3",
     });

(Action will always have the default value "storeaction")

Note that you need to define this route befaure the default generic route so it doesn't catch it before this kicks in.