【问题标题】:Format decimal value with comma MVC 5用逗号格式化十进制值 MVC 5
【发布时间】:2017-04-29 22:30:59
【问题描述】:

我有问题! 我正在使用 Mvc5,并且我有这样的属性。

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

还有剃须刀:

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

此时没有错误。但如果我发送 1.300,40,我总是得到 0。

但是,如果我发送 1300,40,我会得到正确的值。 我该如何解决?我想得到正确的值,如果我发送 1300,50 或 1.300,40

【问题讨论】:

  • 您能确认. 只是格式化千位分隔符,而, 是十进制分隔符吗?
  • 是的,你是对的
  • 我不想像这个函数一样在 onsubmit 之前使用 when 。 $(this).val($(this).val().replace(".", "")); );
  • 延伸阅读:stackoverflow.com/questions/32236013/…haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx。基本上,模型绑定系统不支持开箱即用地格式化数千个分隔符。您可以应用自己的类型描述符和/或模型绑定器来处理这种情况。
  • 非常感谢你! @ChadT

标签: c# asp.net asp.net-mvc string-formatting


【解决方案1】:

您必须添加自己的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;
    }
}

并在您的 Application_Start 中注册它:

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

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

【讨论】:

  • 哇!我一直想要这样的东西!恭喜你,我的朋友。
【解决方案2】:

如果我们想为所有 c# 值类型使用通用 ModelBinder,那么

using System;
using System.Globalization;
using System.Web.Mvc;
public class ValueTypeModelBinder<T> : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var modelState = new ModelState { Value = valueResult };
        var result = default(T);

        try
        {
            var srcValue = valueResult.AttemptedValue;
            var targetType = typeof(T);

            //Hp --> Logic: Check whether target type is nullable (or) not? 
            //If Yes, Take underlying type for value conversion.
            if (targetType.IsGenericType &&
                targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            if (targetType.IsValueType && (!string.IsNullOrWhiteSpace(srcValue)))
            {
                result = (T)Convert.ChangeType(srcValue, targetType, CultureInfo.CurrentUICulture);
            }
        }
        catch (Exception ex)
        {
            modelState.Errors.Add(ex);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return result;
    }
}

添加上述类后,在Global.asax.cs文件的“Application_Start”方法下配置ModelBinders。

using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ModelBinders.Binders.Add(typeof(decimal?), new ValueTypeModelBinder<decimal?>());
        ModelBinders.Binders.Add(typeof(decimal), new ValueTypeModelBinder<decimal>());
        ModelBinders.Binders.Add(typeof(int), new ValueTypeModelBinder<int>());
        ModelBinders.Binders.Add(typeof(double?), new ValueTypeModelBinder<double?>());
    }
}

【讨论】:

    猜你喜欢
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多