Search code examples
c#asp.net-mvcasp.net-mvc-routing

RedirectToAction As Get Request format


I have an action result that I want to redirect to an action with a dynamic ID.

  return RedirectToAction("Engine", new {id = latestVersion.Id});

However, the URL that returns ends up being:

domain.com/project/engine/xxx

what I need however is it to be:

domain.com/project/engine?id=xxx

Here are my current maproutes:

  routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    routes.MapRoute(
        "PrevSession", // Route name
        "{controller}/{action}/{id}/{id2}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional, id2 = UrlParameter.Optional } // Parameter defaults
    );

Is there a way to change the way this is formatted at the controller level?


Solution

  • Option 1.

    you can change the id route param to some other name like,

    routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{myId}", // URL with parameters
                new { controller = "Home", action = "Index", myId = UrlParameter.Optional } // Parameter defaults
            );
    

    and change accordingly in the controllers(where they are used), or

    Option 2.

    You can add a dummy route definition without id parameter like,

    routes.MapRoute(
                    "RouteWithoutId", // Route name
                    "{controller}/{action}" 
                );
    

    and use RedirectToRoute method like,

    return RedirectToRoute("RouteWithoutId", new { action = "Engine", id = latestVersion.Id});
    

    hope this helps.