C# – Building a language switcher – 2 languages only – ASP.NET MVC

asp.net-mvcc++switch-statement

ASP.NET MVC app, close to completion, then it was decided that it needed a language switcher. It will simply be two languages: English and Japanese. They should be able to switch between the two, but if one is not selected it should choose whichever is the default language of the browser.

I'm wondering what the best solution would be in this case.

First thought, routes! So I change the routes to have a /{l} on the end of every route, and defaulted l = "". Then, in my BaseController (every controller is based off of it), I check the l variable in the route. Each action returns a view based on the language.

I wanted to simply be able to hack /ja-jp on the end of the url, and it would show the view in Japanese. It didn't quite seem to route correctly. Then, I was real bad in my views and hand coded the links… I couldn't quite get the helper to output the right links at first… and got into a bad habit of hand coding them. So, I'd have to re-code every link again – to hack the language variable on the end.

Second thought… ok, use jQuery to append the language variable to all anchor's href. That seems overly clumsy and difficult in certain situations where hrefs are hidden until needed, etc…

So… at this point I've decided to just do whatever it takes. What is the most elegant way to switch between 2 languages – without using resource files? I simply want the action to choose between 2 views, based on language.

Do I rewrite every link I've got to use the Html helper and then get the routes working? Then in the BaseController just set the language to English if their is no value?

Any advice is much appreciated, thank you.

Best Solution

I think one of the most easiest and user-friendly method is to use the domain (sub-domain actually) to identify what language it speaks. It doesn't need to change almost anything in the Html helper (those HTML.ActionLink) since it works only relatively to domain. Also, it might looks neat to user that when seeing that domain, they know exactly what language it supposed to be, and without making the url too long. All you need to do is to do something in the language switcher to work.

No matter what approach, I strongly discourage using the second thought, since you can't deny (even 0.1%) people not having javascript to work to visit your japanese web site, right?