I have this route declaration:
routes.MapRoute(
// Route name
"WhiteLabelPartners",
// URL with parameters
"partners/{partnerName}/{controller}/{action}/{id}",
// Parameter defaults
new { partnerName = "", controller = "", action = "index", id = UrlParameter.Optional }
);
When I try this URL:
/partners/a/savings/index/1
…it works fine. The index action of the Savings controller is hit.
But, when I try this URL:
/partners/a/savings/index
I get a “not found”.
If I have a UrlParameter.Optional for the {id} parameter, why is it still being required?
Could anyone explain? How can I make the {id} parameter optional?
Thanks
Make sure your Index Action does not expect a parameter.
If, on your controller, your Index action looks like this :
public ActionResult Index(int id)
it will need a param to be passed in the ID field, as you are not providing a default value in the route. That’s probably why you are getting the ‘not found’error as it cannot find a matching action. It is expecting :
public ActionResult Index()
You could leave the Index() action without a parameter and from within the Index() action, retrieve the value of the passed in ‘id’ parameter, if any via :
RouteData.Values["id"]
to use it.
Let us know if that works for you.
(note: i wanted to post a comment like tejs(but dont see a link to add comment?!), to ask you to show your Index method signature on the controller, so please do include that in the question.)