Reputation: 826
I have a decimal field in my modal.
public partial class MyModel
{
public decimal? BudgetAantalDecimal { get; set; }
}
I show this in my form with
@Html.EditorFor(model => model.BudgetAantalDecimal, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
When I fill in the value 100 the field is filled in the model. When I fill in the value 100.66 the value is null in my model.
When I change my language setting from Dutch to US format I can use the value 100.66. My customer has the Dutch language setting set in Windows. How can I overcome this issue?
Upvotes: 0
Views: 1001
Reputation: 12815
You'll need to add a custom model binder to deal with the changing punctuation when it comes to decimals. This blog goes over step by step, but I'll recreate some here in case the link breaks.
First, you need to create the binder:
public class DecimalModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
var actualValue = null;
try {
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e) {
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
After that, all you need to do is add it to your config so it knows about it:
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
// All that other stuff you usually put in here...
}
Upvotes: 1