默认 ASP.NET MVC 3 模型绑定器不绑定十进制属性 [英] Default ASP.NET MVC 3 model binder doesn't bind decimal properties

查看:25
本文介绍了默认 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的源代码后,似乎问题是asp.net mvc使用框架的类型转换器进行转换,出于某种原因对于 int 到十进制的转换返回 false,我最终使用了自定义模型绑定器提供程序和小数的模型绑定器,您可以在这里看到它:

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 Convert.ToDecimal(valueProviderResult.AttemptedValue);
    }    

    #endregion
}

要注册这个 ModelBinder,只需在 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天全站免登陆