Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can 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}

rather than

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

I tried setting up a route as follows:

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

But this doesn't work because I am unable to make the id parameter optional.

The following URLs do work:

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

But these URLs do not:

/campaign/create
/campaign/indexempty

MVC just calls Index for both. What am I doing wrong?

like image 466
parleer Avatar asked Nov 29 '11 16:11

parleer


1 Answers

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" } 
        );
like image 190
John Allers Avatar answered Nov 04 '22 01:11

John Allers