Search code examples
c#asp.netasp.net-mvcstring-formatting

Format decimal value with comma MVC 5


I have a problem! I am using Mvc5, and I have a property like this.

[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal Total { get; set; }

And razor :

@Html.EditorFor(modelItem => Model.Total, new { htmlAttributes = new { @class = "form-control input-sm" } })

There is not error at this point. But if I send like 1.300,40 I getting always 0.

But if I send like 1300,40 I getting correct value. How can I solve it? I want get correct value, if I send 1300,50 or 1.300,40


Solution

  • You will have to add your own ModelBinder:

    public class DecimalModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var modelState = new ModelState { Value = valueResult };
            decimal actualValue = 0;
    
            try
            {
                actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                    CultureInfo.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }
    
            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
    }
    

    and register it in your Application_Start:

    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    

    Reference: http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/