parleer
parleer

Reputation: 1370

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?

Upvotes: 5

Views: 1237

Answers (1)

John Allers
John Allers

Reputation: 3122

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" } 
        );

Upvotes: 7

Related Questions