Created
May 17, 2011 20:27
-
-
Save jonathascosta/977309 to your computer and use it in GitHub Desktop.
Localized Model Binder for specified culture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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