Last active
July 27, 2017 09:37
-
-
Save johnnyreilly/5135647 to your computer and use it in GitHub Desktop.
Phil Haacks DecimalModelBinder adapted to handle nullable decimals
This file contains 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
using System; | |
using System.Globalization; | |
using System.Web.Mvc; | |
namespace My.ModelBinders | |
{ | |
/// <summary> | |
/// Thank you Phil Haack: used to model bind multiple culture decimals | |
/// http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx | |
/// | |
/// Use by adding these 2 lines to Application_Start in Global.asax.cs: | |
/// | |
/// System.Web.Mvc.ModelBinders.Binders.Add(typeof(decimal), new ModelBinders.DecimalModelBinder()); | |
/// System.Web.Mvc.ModelBinders.Binders.Add(typeof(decimal?), new ModelBinders.DecimalModelBinder()); | |
/// </summary> | |
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 | |
{ | |
//Check if this is a nullable decimal and a null or empty string has been passed | |
var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType && | |
string.IsNullOrEmpty(valueResult.AttemptedValue)); | |
//If not nullable and null then we should try and parse the decimal | |
if (!isNullableAndNull) | |
{ | |
actualValue = decimal.Parse(valueResult.AttemptedValue, NumberStyles.Any, 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