【问题标题】:Decimal numbers in ASP.NET MVC 5 appASP.NET MVC 5 应用程序中的十进制数
【发布时间】:2017-02-09 17:58:11
【问题描述】:

我对十进制数字有疑问。

如果我在文本框中使用 .(dot) 而不是 ,(comma) 它在控制器中为 null。

我知道这是一个语言问题,因为在西班牙语中我们使用逗号而不是小数点,但我需要使用点。

这个可以改吗?

这很奇怪,因为在控制器中我必须使用 .(dot) 来表示小数,即:

float x = 3.14 可以,但float x = 3,14 不能,所以我不明白...在某些情况下我必须使用点...在其他情况下我必须使用逗号...

这是我的代码:

在模型中:

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

鉴于:

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

在控制器中:

public ActionResult Create([Bind(Include = "ID,Codigo,Fecha,Trabajo,Notas,BaseImponible,Iva,Total,Verificado,FormaDePagoID,ClienteID")] Presupuesto presupuesto)
    {

【问题讨论】:

  • 如果这是 ASP.NET MVC,正确的标签应该是 asp.net-mvc(如果你阅读了这些描述,应该会清楚)

标签: c# asp.net-mvc


【解决方案1】:

谢谢大家。我发现这个code from Phil Haack 效果很好。

在项目的任何文件夹中创建一个类

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;
        }
    }
}

将此添加到 Global.asax 中的 Application_Start() 方法

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

现在使用十进制类型而不是浮点或双精度,一切都会好起来的! 谢谢各位小伙伴们见分晓!。

【讨论】:

  • 你能做同样的事情并仍然使用双吗?
【解决方案2】:

您的控制器使用 C#。特定语言声明 . 是小数分隔符。时期。这不是特定于语言的,仅此而已。

您的数据库或 UI(使用服务器的语言设置)可能会使用不同于 C# 使用的默认(美国)语言设置的其他小数分隔符。这就是为什么你必须在那里使用, 作为分隔符。

【讨论】:

    【解决方案3】:

    您需要使用自定义模型绑定器。

    查看这篇博文http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

    【讨论】:

      【解决方案4】:

      如果您希望根据 UI 文化在 UI 中将逗号 (,) 分隔的十进制输入转换为点 (.) 以绑定到 C# 十进制数,您可以使用 Asp.Net MVC 的自定义模型绑定器,其中采用逗号分隔的十进制字符串并将逗号替换为点,然后分配给 C# 十进制属性。

      优势在于,它可在整个应用程序中重复使用,您可能会在其中重复使用十进制转换的场景。

      希望以下链接对您有所帮助:

      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/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-05
        • 2015-02-09
        • 1970-01-01
        • 2023-03-25
        • 2011-09-23
        • 1970-01-01
        相关资源
        最近更新 更多