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

Differentiate MVC routing for {Controller}/parameter to {Controller}/{action}?param=myvalue


I must be able to deal with a route like this: MyController/ElementType For that purpose I've created a custom route like this:

  context.MapRoute(
                  "NameOfTheRoute",
                  "MyPath/{controller}/{elementType}",
                  new { controller = "Elements", action = "Create" }
                  );

And it works fine, the problem is when I have a route like /MyPath/Elements/GetElementType?elementType=fire88

GetElementType is a different action, but it goes to the Create action because of the custom route I declared before, how can I let know the routing they are different actions?


Solution

  • the reason why it going to this route because you didn't define a route to handle action so MyPath/{controller}/{elementType} means after the name of controller everything will be considered as {elementType} so you have to create another another route which will handle action

    routes.MapRoute(
        "MyPathRouteWithAction",
        "MyPath/{controller}/{action}/{elementType}",
        new {controller = "Elements", action = "Create"}
    );
    
    routes.MapRoute(
        "NameOfTheRoute",
        "MyPath/{controller}/{elementType}",
        new {controller = "Elements", action = "Create"}
    );
    

    the first custom route will handle routs like /MyPath/Elements/GetElementType/fire88