In my model, do I have the following decimal place? Property:
public decimal? Budget { get; set; }
I understand that I need a custom decimal binder that Haack provided at the following link: http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx .
I changed its code so that if the passed value contains a currency symbol and / or a comma, I disable it and then try to convert it to decimal. This works, but since my property is a null decimal type, I also want it to not accept anything and move in its own fun way by inserting zero into this column in my database. Now it inserts 0.00. I know that I have something missing in my code, but I have a brain freeze.
Here's the binding code:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); ModelState modelState = new ModelState { Value = valueResult }; object actualValue = null; object newValue = null; try { if (!string.IsNullOrEmpty(valueResult.AttemptedValue)) { newValue = valueResult.AttemptedValue.Replace("$", "").Replace(",", ""); } actualValue = Convert.ToDecimal(newValue, CultureInfo.CurrentCulture); } catch (FormatException e) { modelState.Errors.Add(e); } bindingContext.ModelState.Add(bindingContext.ModelName, modelState); return actualValue; }
Again, the goal is to have a decimal place? acts as usual, but if there is a value that contains a currency symbol and / or a comma, and it can be converted to decimal, and then returned.
thanks
asp.net-mvc-3
Mike
source share