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

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

问题描述

我在我的控制器中的JsonResult方法接受一个对象作为参数。这一个对象的属性是一个有三个可能的值枚举。我以为,当客户端在该属性一个int通过它将填充枚举,但它没有,它默认为0,枚举被设置为第一它是可能的选择。

I have a JsonResult method in my controller that accepts an object as an argument. 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中默认的模型粘合剂。正确的整数值,使得它模型绑定,但粘合剂是不是codeD映射到枚举的整数值。如果传递的是包含枚举的命名值的字符串值它正确地结合。这样做的问题是,当你使用它发出的整数值枚举值,而不是指定的值 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.$c$ctunnel.com/how-to-bind-to-enums-on-json-objects-in-aspnet-mvc-3

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

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