Skip to content

Instantly share code, notes, and snippets.

@jpogran
Created April 26, 2011 12:56
Show Gist options
  • Save jpogran/942210 to your computer and use it in GitHub Desktop.
Save jpogran/942210 to your computer and use it in GitHub Desktop.
decimal model binder asp.net mvc
//http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx
//protected void Application_Start() {
//ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
// Your other stuff goes here.
//}
public class DecimalModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext) {
ValueProviderResult valueResult = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
try {
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e) {
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment