简体   繁体   English

ASP.NET MVC 5应用程序中的十进制数字

[英]Decimal numbers in ASP.NET MVC 5 app

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 ie: 这很奇怪,因为在控制器中我必须使用。(点)表示小数,即:

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... 我可以做float x = 3.14但我不能做float x = 3,14所以我不明白这...在某些情况下我必须使用点...在其他情况下我必须使用逗号...

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)
    {

Thanks everybody. 谢谢大家。 I found this code from Phil Haack that works pretty well. 我发现这个来自Phil Haack的代码效果非常好。

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 将其添加到Global.asax中的Application_Start()方法

    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 !. 谢谢伙伴见到你!

Your controller uses C#. 您的控制器使用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. 您的数据库或UI(使用服务器的语言设置)可能使用另一个小数分隔符,而不是C#使用的默认(美国)语言设置。 That's why you have to use , as separator there. 这就是为什么你必须使用,作为分隔符。

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/ 请参阅此博客文章http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

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. 如果你希望你的逗号(,)根据UI文化在UI中分隔十进制输入,要转换为点(。)以绑定到C#十进制数,你可以去Asp.Net MVC的自定义模型绑定器,其中以逗号分隔十进制字符串并用点替换逗号,然后分配给C#decimal属性。

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/ ASP.Net MVC自定义模型绑定说明 http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx http:// haacked的.com /存档/ 2011/03/19 /固定结合到decimals.aspx /

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM