Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call different (localized) view based on current culture

I'm using LocalizationAttribute which implements ActionFilterAttribute to localize views. I simply put [Localize] on controller. I was using LocalizeStrings.resx files to apply based on which language is on current thread. Everything works for this simple case (with localized strings). Now I want to localize complete pages (not just strings).

To acomplish this which approach do you use?

Do I need to identify which thread is current on controller and based on that value to call view:

public ActionResult AboutUs()
{
    switch (Thread.CurrentThread.CurrentUICulture.Name)
    {
        case "en-US":
            return View("EnglishUSView");               
        case "de-DE":
            return View("GermanView");              
        default:
            return View(); 
    }
    return View();
}

or do you recommend something else ?

like image 491
user1765862 Avatar asked Dec 27 '22 04:12

user1765862


1 Answers

I would recommend to simply extended RazorViewEngine and override FindPartialView and FindView in order to inform ViewEngine to look is there view with current culture inside thread. If that page cannot be found than proceed as usuall.

  1. Extend RazorViewEngine
  2. Inside View folder there should be (assuming that english is default lang.) Index.cshtml and Index.de-DE.cshtml
  3. Modify Global.asax.cs file, inside application start you should call localized view engine (the one which implements RazorViewEngine)

Controller

no further modification needed

Views

/Views/Home/Index.cshtml
/Views/Home/Index.de.DE.cshtml

Helper

public class LocalizedRazorViewEngine : RazorViewEngine
{
   public override ViewEngineResult FindPartialView ...
   public override ViewEngineResult FindView...
}

ApplicationStart

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new LocalizedRazorViewEngine());
like image 170
BobRock Avatar answered Jan 16 '23 01:01

BobRock