Click here to Skip to main content
Click here to Skip to main content
Technical Blog

ASP.NET MVC localization using ActionFilter

, 18 Sep 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
ASP.NET MVC localization using ActionFilter

Action filters in ASP.NET MVC provide a great way to apply custom behavior to selected controller actions. They let you execute code before or after the actual action has been executed. That reminds of Aspect Oriented Programming and can be used to apply cross cutting concerns to controllers.

One of the things that first seemed reasonable to apply using action filters was localization. An action filter that sets current thread’s culture before an action is invoked might look like this:

public class LocalizationCacheFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en");
    }
}

When you apply this action filter to your actions, the culture is set before the action, causing any code that is run later, including the action, to use the given culture. Easy and nice, however, there’s a small problem.

It seems that model binding happens before action filters are executed, so that means that model binder will have no idea about a custom culture. That means that any validation that will be made on the model will produce validation error messages for the default culture, not the one you will set in the action filter. JavaScript validation will, however, produce the correct localized error messages, because JavaScript error messages are created at view’s render time and embedded in the output HTML. At that time, the action filter has already have been executed.

This issue caused me some head-scratching. The fix is to set custom culture earlier, in HttpApplication‘s BeginRequest event handler, for example.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gediminas Geigalas
Software Developer (Senior)
Lithuania Lithuania
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411022.1 | Last Updated 18 Sep 2011
Article Copyright 2011 by Gediminas Geigalas
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid