I have a model binder for the user type Money . The binding works fine, but the built-in binding / validation does not work and is marked as invalid.
My binder looks like this:
public class MoneyModelBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { var money = (Money)bindingContext.Model; var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Amount").AttemptedValue; var currencyCode = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Iso3LetterCode").AttemptedValue; Money parsedValue; if (String.IsNullOrEmpty(value)) { money.Amount = null; return; } var currency = Currency.FromIso3LetterCode(currencyCode); if(!Money.TryParse(value, currency, out parsedValue)) { bindingContext.ModelState.AddModelError("Amount", string.Format("Unable to parse {0} as money", value)); } else { money.Amount = parsedValue.Amount; money.Currency = parsedValue.Currency; } } }
When the user enters a value of type "45,000" in the text box, my binder selects the value correctly, analyzes it and sets it into the model.
The problem I have is that the default check is then run in The value '45,000' is not valid for Amount states, which, like the decimal type, makes sense, but I already bound the data. How can I prevent the default data bindings that I have already processed?
I'm not sure if this matters, but I use Html.EditorFor with and an editor that looks like this:
@model Money <div class="input-prepend"> <span class="add-on">@Model.Currency.Symbol</span> @Html.TextBoxFor(m => m.Amount, new{ placeholder=string.Format("{0}", Model.Currency), @class="input-mini", Value=String.Format("{0:n0}", Model.Amount) }) @Html.HiddenFor(x => x.Iso3LetterCode) </div>
source share