Search code examples
c#url-routingasp.net-mvc-5.2

How to set 2 routes point to the same controller in ASP.NET MVC 5


I have an ASP.NET MVC 5 web site which has a controller MyFirstController.

That way, I can load the index view by using https://example.server.com/MyFirst.

On the other hand, I have another view that renders the link (HREF attribute of HTML A tag) this way:

Url.Action("Index", "MyFirst")

That URL rendering causes the link to be generated:

https://example.server.com/MyFirst 

So far, so good. Now, I need to have a route something like this

https://example.server.com/MySecond

That URL should load the same Index view of MyFirst controller without creating a new controller named MySecondController. This is like having a MyFirst controller alias named MySecond.

In RouteConfig.cs file I added this:

routes.MapRoute(name: "MySecond",
                url: "MySecond/{action}/{id}",
                defaults: new { controller = "MyFirst", action = "Index", id = UrlParameter.Optional }
               );

The problem I have with this code is that I have this rendering code in the other view:

@if (somecondition)
{
    ... Url.Action("Index", "MyFirst") ...
}
else
{
    ... Url.Action("Index", "MySecond") ...
}

I need that if somecondition is true, the rendered URL to be https://example.server.com/MyFirst and if it is false, the rendered URL to be https://example.server.com/MySecond.

The problem I am having is that both are being rendered as https://example.server.com/MySecond.

How can I accomplish this task?


Solution

  • Instead of using Url.Action, use Url.Route as it allows to explictly pass the name of the route to apply for rendering the url.

    To render the /MySecond url, pass the name of the MySecond route.

    @Url.RouteUrl("MySecond")
    

    Do the same to render the /MyFirst url, but since it doesn't have an explicit route name, you'll have to pass both the name of the default route and the name of the MyFirst controller.

    @Url.RouteUrl("Default", new { Controller = "MyFirst" })
    

    You can omit the name of the Index action, as it has been set up as the default one.