Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal numbers in ASP.NET MVC 5 app

Tags:

c#

asp.net-mvc

I have a problem with decimal numbers.

If I use .(dot) instead of ,(comma) in the textbox it comes null in controller.

I know its a language issue because in spanish we use comma instead of dot for decimals but I need to use dot.

It is possible to change this?

It is strange because in controller I have to use .(dot) for decimals i.e:

I can do float x = 3.14 but I can not do float x = 3,14 so I do not understand this... In some cases I have to use dot... In others I have to use comma...

This is my code:

In model:

[Display(Name = "Total")]
public double Total { get; set; }

In view:

@Html.EditorFor(model => model.Total, new { id = "Total", htmlAttributes = new {@class = "form-control" } })

In controller:

public ActionResult Create([Bind(Include = "ID,Codigo,Fecha,Trabajo,Notas,BaseImponible,Iva,Total,Verificado,FormaDePagoID,ClienteID")] Presupuesto presupuesto)
    {
like image 839
Txentxo Txentxako Avatar asked Sep 15 '14 13:09

Txentxo Txentxako


1 Answers

Thanks everybody. I found this code from Phil Haack that works pretty well.

Create a class in any folder of your project

public class ModelBinder
{
    public class DecimalModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext,
                                         ModelBindingContext bindingContext)
        {
            object result = null;

            // Don't do this here!
            // It might do bindingContext.ModelState.AddModelError
            // and there is no RemoveModelError!
            // 
            // result = base.BindModel(controllerContext, bindingContext);

            string modelName = bindingContext.ModelName;
            string attemptedValue =
                bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

            // Depending on CultureInfo, the NumberDecimalSeparator can be "," or "."
            // Both "." and "," should be accepted, but aren't.
            string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
            string alternateSeperator = (wantedSeperator == "," ? "." : ",");

            if (attemptedValue.IndexOf(wantedSeperator) == -1
                && attemptedValue.IndexOf(alternateSeperator) != -1)
            {
                attemptedValue =
                    attemptedValue.Replace(alternateSeperator, wantedSeperator);
            }

            try
            {
                if (bindingContext.ModelMetadata.IsNullableValueType
                    && string.IsNullOrWhiteSpace(attemptedValue))
                {
                    return null;
                }

                result = decimal.Parse(attemptedValue, NumberStyles.Any);
            }
            catch (FormatException e)
            {
                bindingContext.ModelState.AddModelError(modelName, e);
            }

            return result;
        }
    }
}

Add this to Application_Start() method in Global.asax

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

Now use decimal type instead of float or double and everything will go fine !! Thank you mates see you around !.

like image 135
Txentxo Txentxako Avatar answered Oct 26 '22 05:10

Txentxo Txentxako