Change the controller and action name according to the selected language

I have a controller named "Hem" and "Action" is "Om". And the default language I set is Swedish. So the route will be on the Swedish site, this

/sv/Hem/Om

Now I want to change the language to "en" by clicking the "English" button. Thus, the route will be automatically set this way:

/en/Home/About

But the functionality should be work /sv/Hem/Om, and in the address bar should be displayed as/en/Home/About

Experts you can help me.

+4
source share
3 answers

You can do it.

routes.MapRoute(
    "English route",
    "en/{controller}/{action}/{id}"
    new { controller = "Home", action = "Index", language = "en" },
);

routes.MapRoute(
    "FrenchHome",
    "/sv/Hem/Om",
    new { controller = "Home", action = "Index", language = "fr" }
);

or you can do this:

public class GenericRoutes
{
    public string Controller {get;set;}
    public string Action {get;set;}
    public string Url{get;set;}
    public string RouteName{get;set;}
}

public List<GenericRoutes> Routes = new List<GenericRoutes>();

Routes.Add(new GenericRoutes{Cotroller="bl",Action="cl",Url="bl/cl"})

for(int i=0;i<Routes.count();i++) 
{
    routes.MapRoute(
        Routes[i].RouteName,
        Routes[i].Url,
        new { controller = Routes[i].Controller, action = Routes[i].Action },
    );
}
+7

. , , , . ASP.net , .

. , http-Accept-Language, , . , , .

, . 2 3 , . , , - . " " , -, , , , , .

, .net , , :)

Scott Hanselman - MVC 3 + JQuery

+2

, . , , .

, , .

:

RegisterRoutes ,

public static void RegisterRoutes(RouteCollection routes)
{}
  • url ( url (en ))

  • , foreach.

.

foreach (var route in RouteValues)
{
    route.UniqueName,
    routes.MapRoute("prefix/{controller}/{action}/{id}, 
       new { controller = route.Controller , action = route.Action , id = route.Id  });
}
0

Source: https://habr.com/ru/post/1624642/


All Articles