繁体   English   中英

用逗号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;
    }
}

添加上述类之后,在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?>());
    }
}

暂无
暂无

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

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