Click here to Skip to main content
15,885,026 members
Articles / Web Development / HTML

ASP.NET MVC localization using ActionFilter

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Sep 2011CPOL1 min read 14K   2  
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:

C#
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)


Written By
Software Developer (Senior)
Lithuania Lithuania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --