Skip to content

Instantly share code, notes, and snippets.

@khellang
Created March 25, 2013 15:53
Show Gist options
  • Save khellang/5238138 to your computer and use it in GitHub Desktop.
Save khellang/5238138 to your computer and use it in GitHub Desktop.
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
object actualValue = null;
if (string.IsNullOrEmpty(valueResult.AttemptedValue))
{
actualValue = bindingContext.ModelType.IsValueType
? Activator.CreateInstance(bindingContext.ModelType) : null;
}
else
{
try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.GetCultureInfo("nb-NO"));
}
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