默认的ASP.NET MVC 3模型绑定不绑定小数性质 [英] Default ASP.NET MVC 3 model binder doesn't bind decimal properties

查看:192
本文介绍了默认的ASP.NET MVC 3模型绑定不绑定小数性质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,当我这个JSON发送到一个动作:

For some reason, when I send this JSON to an action:

{"BaseLoanAmount": 5000}

这是应该被绑定到一个名为BaseLoanAmount十进制属性的模型

,它不绑定,它只是停留0.不过,如果我送:

which is supposed to be bound to a model with a decimal property named "BaseLoanAmount", it doesn't bind, it just stays 0. But if I send:

{"BaseLoanAmount": 5000.00}

它不绑定属性,但为什么呢?不能5000被转换为十进制事件,如果它不具有十进制数?

it does bind the property, but why? Can't 5000 be converted to a decimal event if it doesn't have decimal numbers?

推荐答案

步入asp.net MVC的源$ C ​​$ C后,seemsd的问题是,在转换asp.net MVC使用框架的类型转换器,其出于某种原因,返回一个int十进制转换假的,我结束了使用小数自定义模型粘合剂供应商和模型绑定,你可以在这里看到:

After stepping into asp.net mvc's source code, it seemsd the problem is that for the conversion asp.net mvc uses the framework's type converter, which for some reason returns false for an int to decimal conversion, I ended up using a custom model binder provider and model binder for decimals, you can see it here:

public class DecimalModelBinder : DefaultModelBinder
{
    #region Implementation of IModelBinder

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (valueProviderResult.AttemptedValue.Equals("N.aN") ||
            valueProviderResult.AttemptedValue.Equals("NaN") ||
            valueProviderResult.AttemptedValue.Equals("Infini.ty") ||
            valueProviderResult.AttemptedValue.Equals("Infinity") ||
            string.IsNullOrEmpty(valueProviderResult.AttemptedValue))
            return 0m;

        return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Convert.ToDecimal(valueProviderResult.AttemptedValue);
    }    

    #endregion
}

要注册这个模型绑定器,只要把下面的行内的Application_Start()

To register this ModelBinder, just put the following line inside Application_Start():

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

这篇关于默认的ASP.NET MVC 3模型绑定不绑定小数性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆