用逗号 MVC 5 格式化十进制值

Format decimal value with comma MVC 5

我有问题! 我正在使用 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

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

以防万一,如果我们想为所有 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;
    }
}

添加以上class后,在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?>());
    }
}