I want to create a website in different languages. I already read that I could create an ActionFilter, but I have a litte problem:
I had to create a custom ModelBinder in order to work with english and german number formats (123,456,789.1
vs. 123.456.789,1
)
public class DecimalModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string key = bindingContext.ModelName;
var v = ((string[])bindingContext.ValueProvider.GetValue(key).RawValue)[0];
float outPut;
if (float.TryParse(v, NumberStyles.Number, System.Globalization.CultureInfo.CurrentCulture, out outPut))
return outPut;
return base.BindModel(controllerContext, bindingContext);
}
}
This ModelBinder uses the current culture to decide which format is used. But unfortunatly, the ModelBinder is used before the ActionFilter could change the culture.
How can I change the culture before the ModelBinder becomes active?
You can implement an IHttpModule and set the culture in the BeginRequest, as seen here.
void context_BeginRequest(object sender, EventArgs e)
{
// eat the cookie (if any) and set the culture
if (HttpContext.Current.Request.Cookies["lang"] != null)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
string lang = cookie.Value;
var culture = new System.Globalization.CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}