Search code examples
c#asp.net-mvcrazorurl-routingasp.net-mvc-routing

ActionLink shows wrong url


I have some pre-defined URLs in routing table actually directing to same controller and action, but different language. For example

            routes.MapRoute(
            "Contact", // Route name
            "contact", // URL with parameters
            new { controller = "Home", action = "Contact", lang="en" } // Parameter defaults
            );

            routes.MapRoute(
            "Contact2", // Route name
            "iletisim", // URL with parameters
            new { controller = "Home", action = "Contact", lang="tr" } // Parameter defaults
            );

When i use Html.ActionLink in View and run application, URL shows the first route, for example:

@Html.ActionLink(Resources.Contact, "Contact", "Home")

When current language is tr when page rendered URL is : /contact which should be /iletisim instead.

When i change the order of route mappings then en language pages shows wrong URL.

How can I solve this problem?


Solution

  • When matching a route from ActionLink, you must take all of the parameters that the route generates into consideration. The framework will always return the first match for the supplied route values.

    In your case, you are supplying the route values:

    controller = "Home"
    action = "Contact"
    

    Which given the lack of other information will match your Contact route (the first route with controller = "Home", action = "Contact").

    If you want to match a specific route, then you need to pass the lang route value as well.

    @Html.ActionLink(Resources.Contact, "Contact", "Home", new { lang = "tr" }, null)
    

    That will match the Contact2 route.

    Alternatively, you can put the lang into the URL of the page, which would ensure that it is part of the current request as shown in ASP.NET MVC 5 culture in route and url . Then MVC will automatically supply this value to all of your ActionLinks and other UrlHelper based methods.