Search code examples
c#asp.net-mvcglobalizationresxspark-view-engine

Spark Globalization with ASP.NET MVC


I am using the spark viewengine, asp.net mvc, and .resx files.

I want to set a language through my custom SessionModel (Session) which is registered through Castle.Windsor and has a string property of Culture which can be set by the user...

I need the current language to persist on every view, without having to constantly set the current UICulture.

Not having to do this everytime in each Controller Action:

    public SessionModel SessionModel { get; set; }

    public ActionResult Index()
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SessionModel.Culture);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }

The problem with doing it this way, is if I go onto another page the current culture will flip back to the default language.

On the spark view I simply call, to obtain the current Culture:

${SR.Home}

SR.resx contains a public entry for Home.

Does anyone have a good idea of how to do this, should I do this with an ActionFilter?


Solution

  • Action filter seems like a good idea:

    public class SetCultureActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            CultureInfo culture = FetchCultureFromContext(filterContext);
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
            base.OnActionExecuting(filterContext);
        }
    
        private CultureInfo FetchCultureFromContext(ActionExecutingContext filterContext)
        {
            throw new NotImplementedException();
        }
    }
    

    and then decorate your base controller with this attribute.