.NET MVC 3 Custom Decimal? Model Binder

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

+8
asp.net-mvc-3
source share
2 answers

In the try block, I think you need something like

 string valToCheck = valueResult.AttemptedValue; if(valToCheck == string.Empty) { actualValue = null; } else { actualValue = Convert.ToDecimal(valToCheck.Replace("$", string.Empty), CultureInfo.InvariantCulture); } 

In your code, you always set actualValue to the result of ToDecimal ().

+1
source share

You are probably better off using native support for handling NumberStyles . By doing this, you can explain more than the usual dollar sign, but you can also handle pounds, yen, etc.

 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult valueResult = bindingContext.ValueProvider .GetValue(bindingContext.ModelName); ModelState modelState = new ModelState { Value = valueResult }; object actualValue = null; try { if(!string.IsNullOrWhiteSpace(valueResult.AttemptedValue)) actualValue = Decimal.Parse(valueResult.AttemptedValue, NumberStyles.Currency, CultureInfo.CurrentCulture); } catch (FormatException e) { modelState.Errors.Add(e); } bindingContext.ModelState.Add(bindingContext.ModelName, modelState); return actualValue; } 
+8
source share

All Articles