且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

默认 ASP.NET MVC 3 模型绑定器不绑定十进制属性

更新时间:2022-06-10 02:21:30

进入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());