Skip to content

Instantly share code, notes, and snippets.

@jonathascosta
Created May 17, 2011 20:27
Show Gist options
  • Save jonathascosta/977309 to your computer and use it in GitHub Desktop.
Save jonathascosta/977309 to your computer and use it in GitHub Desktop.
Localized Model Binder for specified culture
public class LocalizedModelBinder : DefaultModelBinder
{
private readonly CultureInfo _cultureInfo;
public LocalizedModelBinder(string cultureName)
{
_cultureInfo = CultureInfo.GetCultureInfo(cultureName);
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string attemptedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
if (!string.IsNullOrEmpty(attemptedValue))
{
if (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?))
return DateTime.Parse(attemptedValue, _cultureInfo);
else if (bindingContext.ModelType == typeof(decimal) || bindingContext.ModelType == typeof(decimal?))
return decimal.Parse(attemptedValue, _cultureInfo);
else if (bindingContext.ModelType == typeof(float) || bindingContext.ModelType == typeof(float?))
return float.Parse(attemptedValue, _cultureInfo);
else if (bindingContext.ModelType == typeof(double) || bindingContext.ModelType == typeof(double?))
return double.Parse(attemptedValue, _cultureInfo);
}
return base.BindModel(controllerContext, bindingContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment