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?
Instead of using
Url.Action, useUrl.Routeas it allows to explictly pass the name of the route to apply for rendering the url.To render the
/MySecondurl, pass the name of theMySecondroute.Do the same to render the
/MyFirsturl, 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 theMyFirstcontroller.You can omit the name of the
Indexaction, as it has been set up as the default one.