I have a MVC4 application that has some optional parameters in one of my routes. When two route parameters don't have values the url appears like this "http://localhost:51424/MSDS/UpdateSupplier/SupplierNameHere//"
Is there any way to not have "//" show at the end? The route currently works but I think it looks a little goofy
Here is my route
routes.MapRoute(
name: "MSDS Update Supplier",
url: "MSDS/{action}/{supplier}/{Part_No}/{Product_ID}",
defaults: new { controller = "MSDS", action = "Index", supplier = UrlParameter.Optional, Part_No = UrlParameter.Optional, Product_ID = UrlParameter.Optional }
);
Is there any way to not have "//" show at the end?
Yes, you can get rid of the optional parameters. Technically, there should only be one optional parameter per route anyway.
You can accomplish the same by building up a set of routes from most specific to least specific that each handle a specific number of segments. The application will still work the same after it is routed, the only difference is it will match a different route depending on how many segments and then build the URL appropriately with the correct number of /
symbols.
routes.MapRoute(
name: "MSDS Update Supplier Part_No Product_ID",
url: "MSDS/{action}/{supplier}/{Part_No}/{Product_ID}",
defaults: new { controller = "MSDS", action = "Index", Product_ID = UrlParameter.Optional }
);
routes.MapRoute(
name: "MSDS Update Supplier",
url: "MSDS/{action}/{supplier}",
defaults: new { controller = "MSDS", action = "Index", supplier = UrlParameter.Optional }
);
Explanation
The first route now have required segments, so they will miss if they are not all supplied and the framework will then try the next route in the list.
So, running the routes from top to bottom, the first route will match MSDS followed by either 3 or 4 more segments.
If MSDS is followed by 1 or 2 segments, it will not match the first route (because it requires at least 3) and match the second route.