R – Creating urls with asp.net MVC and RouteUrl

asp.net-mvcmodel-view-controllerroutes

I would like to get the current URL and append an additional parameter to the url (for example ?id=1)

I have defined a route:

        routes.MapRoute(
            "GigDayListings",                                   // Route name
            "gig/list/{year}/{month}/{day}",                    // URL with parameters
            new { controller = "Gig", action = "List" }         // Parameter defaults
        );

        In my view I have a helper that executes the following code: 

        // Add page index
        _helper.ViewContext.RouteData.Values["id"] = 1;

        // Return link
        var urlHelper = new UrlHelper(_helper.ViewContext);
        return urlHelper.RouteUrl( _helper.ViewContext.RouteData.Values);

However this doesnt work.

If my original URL was :
gig/list/2008/11/01

I get

gig/list/?year=2008&month=11&day=01&id=1

I would like the url to be:
controller/action/2008/11/01?id=1

What am I doing wrong?

Best Answer

The order of the rules makes sence. Try to insert this rule as first.

Also dont forget to define constraints if needed - it will results in better rule matching:

routes.MapRoute(
    "GigDayListings",                                // Route name
    "gig/list/{year}/{month}/{day}",                // URL with parameters
    new { controller = "Gig", action = "List" },    // Parameter defaults
    new
        {
            year = @"^[0-9]+$",
            month = @"^[0-9]+$",
            day = @"^[0-9]+$"
        }    // Constraints
);