模型绑定到 ASP.NET MVC 3 中的枚举 [英] Model Binding to Enums in ASP.NET MVC 3

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

问题描述

我的控制器中有一个方法,它接受一个对象作为参数并返回一个 JsonResult.此对象的属性之一是具有三个可能值的枚举.我假设当客户端为该属性传入一个 int 时,它会填充枚举,但事实并非如此,它默认为 0,并且枚举被设置为第一个可能的选择.

I have a method in my controller that accepts an object as an argument and returns a JsonResult. One of the properties on this object is an enum with three possible values. I assumed that when the client passed in an int for that property it would populate the enum, but it doesn't, it defaults to 0 and the enum is set to the first of it's possible selections.

有什么建议吗?

推荐答案

注意:此问题已在 MVC 4 中解决.如果升级到 MVC 4 是您项目的可行选择,那么仅此而已您必须这样做才能开始将模型绑定到枚举.

NOTE: This has been resolved in MVC 4. If upgrading to MVC 4 is a viable option for your project then that is all you have to do in order to begin model-binding to enums.

也就是说,如果您仍然需要,这里是 MVC 3 的解决方法.

That said, here is the workaround for MVC 3 if you still need it.

问题在于 MVC 中的默认模型绑定器.正确的整数值使其进入模型绑定器,但绑定器未编码以映射到枚举的整数值.如果传入的值是包含枚举命名值的字符串,则它会正确绑定.问题在于,当您使用 Json() 方法将 C# 对象解析为 JSON 时,它会将整数值作为枚举值而不是命名值发送.

The issue is with the default model binder in MVC. The correct integer value makes it to the model binder but the binder is not coded to map to the integer value of the enum. It correctly binds if the value being passed in is a string containing the named value of the enum. The problem with this is that when you parse a C# object into JSON using the Json() method it sends the integer value as the enum value, not the named value.

对此最简单和最透明的解决方法是覆盖默认模型绑定器并编写一些自定义逻辑来修复它绑定枚举的方式.

The easiest and most transparent fix for this is to override the default model binder and write some custom logic to fix the way it binds enums.

  1. 像这样创建一个新类.

  1. Create a new class, like so.

namespace CustomModelBinders
{
    /// <summary>
    /// Override for DefaultModelBinder in order to implement fixes to its behavior.
    /// This model binder inherits from the default model binder. All this does is override the default one,
    /// check if the property is an enum, if so then use custom binding logic to correctly map the enum. If not,
    /// we simply invoke the base model binder (DefaultModelBinder) and let it continue binding as normal.
    /// </summary>
    public class EnumModelBinder : DefaultModelBinder
    {
        /// <summary>
        /// Fix for the default model binder's failure to decode enum types when binding to JSON.
        /// </summary>
        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            var propertyType = propertyDescriptor.PropertyType;
            if (propertyType.IsEnum)
            {
                var providerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (null != providerValue)
                {
                    var value = providerValue.RawValue;
                    if (null != value)
                    {
                        var valueType = value.GetType();
                        if (!valueType.IsEnum)
                        {
                            return Enum.ToObject(propertyType, value);
                        }
                    }
                }
            }
            return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
        }
    }
}

  • 然后只需将其注册到您的 Global.asax 文件中.

  • Then simply register it in your Global.asax file.

    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();
    
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    
        // Register your new model binder
        ModelBinders.Binders.DefaultBinder = new EnumModelBinder();
    }
    

  • 就是这样.枚举现在将正确绑定到 JSON 对象上.

    That's it. Enums will now be correctly bound on JSON objects.

    http://www.codetunnel.com/how-to-bind-to-enums-on-json-objects-in-aspnet-mvc-3

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

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