5

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)
    {
1
  • 1
    If this is ASP.NET MVC, the correct tag would be asp.net-mvc (the descriptions should make this clear if you read them) Commented Sep 15, 2014 at 13:26

4 Answers 4

7

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 !.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you do it the same and still use double?
0

Your controller uses C#. The language specific states that . is the decimal separator. Period. It's not language specific, that's just it.

Your database or UI (which uses the server's language settings) might use another decimal separator than the default (US) language setting C# uses. That's why you have to use , as separator there.

Comments

0

you would need to use a custom model binder.

See this blog post http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

Comments

0

If you want your comma(,) separated decimal input in UI as per UI culture, to be converted to dot(.) to bind to C# decimal number, you can go for Asp.Net MVC's custom model binder, where take the comma separated decimal string and replace the comma with a dot and then assign to the C# decimal property.

The advantage is, its reusable across the application, where you might be having recurring scenarios for decimal conversions.

Hope following links could help you:

ASP.Net MVC Custom Model Binding explanation http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.