title: asp.net MVC 1.0 and 2.0 currency model binding
body: <p>I would like to create model binding functionality so a user can enter ',' '.' etc for currency values which bind to a double value of my ViewModel.</p>
  
  <p>I was able to do this in MVC 1.0 by creating a custom model binder, however since upgrading to MVC 2.0 this functionality no longer works.</p>
  
  <p>Does anyone have any ideas or better solutions for performing this functionality? A better solution would be to use some data annotation or custom attribute.</p>
  
  <pre><code>public class MyViewModel
  {
      public double MyCurrencyValue { get; set; }
  }
  </code></pre>
  
  <p>A preferred solution would be something like this...</p>
  
  <pre><code>public class MyViewModel
  {
      [CurrencyAttribute]
      public double MyCurrencyValue { get; set; }
  }
  </code></pre>
  
  <p>Below is my solution for model binding in MVC 1.0.</p>
  
  <pre><code>public class MyCustomModelBinder : DefaultModelBinder
  {
      public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
      {
          object result = null;
  
          ValueProviderResult valueResult;
          bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out valueResult);
          bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueResult);
  
          if (bindingContext.ModelType == typeof(double))
          {
              string modelName = bindingContext.ModelName;
              string attemptedValue = bindingContext.ValueProvider[modelName].AttemptedValue;
  
              string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
              string alternateSeperator = (wantedSeperator == "," ? "." : ",");
  
              try
              {
                  result = double.Parse(attemptedValue, NumberStyles.Any);
              }
              catch (FormatException e)
              {
                  bindingContext.ModelState.AddModelError(modelName, e);
              }
          }
          else
          {
              result = base.BindModel(controllerContext, bindingContext);
          }
  
          return result;
      }
  }
  </code></pre>