How does my route use optional parameters in the middle of the url using ASP MVC3?

I would like my URLs to use the convention:

/{controller}/{id}/{action}

but not

/{controller}/{action}/{id}

I tried to configure the route as follows:

routes.MapRoute(
            "Campaign",
            "{controller}/{action}/{id}",
            new { controller = "Campaign", action = "Index", id = UrlParameter.Optional } 
        );

But this does not work, because I cannot make the id parameter optional.

The following URLs work :

/campaign/1234/dashboard
/campaign/1234/edit
/campaign/1234/delete

But these URLs are not :

/campaign/create
/campaign/indexempty

MVC just calls Indexfor both. What am I doing wrong?

+5
source share
1 answer

I think you probably need two separate routes for this.

routes.MapRoute(
            "CampaignDetail",
            "{controller}/{id}/{action}",
            new { controller = "Campaign", action = "Index" } 
        );

routes.MapRoute(
            "Campaign",
            "{controller}/{action}",
            new { controller = "Campaign", action = "Index" } 
        );
+7
source

All Articles