Standard MVC model binding cannot parse a value formatted for display . So, you have to write your own connecting device and register it for this type (suppose the type name is Foo):
public class FooModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var result = bindingContext.ValueProvider.GetValue("Amount"); if (result != null) { decimal amount; if (Decimal.TryParse(result.AttemptedValue, NumberStyles.Currency, null, out amount)) return new Foo { Amount = amount }; bindingContext.ModelState.AddModelError("Amount", "Wrong amount format"); } return base.BindModel(controllerContext, bindingContext); } }
Add this binder for type Foo to Application_Start:
ModelBinders.Binders.Add(typeof(Foo), new FooModelBinder());
And, the last - remove the data-val-number attribute from the sum text field (otherwise you continue to see the message that this is not a number):
$("#Amount").removeAttr("data-val-number");
You will now receive a validation error message if the input value is not the correct currency value (for example, $10F.0 ).
BTW I think it is better to use ApplyFormatInEditMode = false than to implement all these things to help MVC bind your own formatted string.
Sergey Berezovskiy
source share