从json到enum的mvc绑定问题(从int到enum的customexception)

Pad*_*Boy 3 model-view-controller binding json

我有这个问题:我使用json将数据发送到服务器.一切正常,但问题是这样的情况:

public enum SexType
{
  Male : 0,
  Female : 1
}

class People{
  public SexType Sex {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

这创造了我的json:

{"Sex" : 0}
Run Code Online (Sandbox Code Playgroud)

当我发送回服务器时,这填补了ModelStateError的问题:从类型'System.Int32'到类型'SexType'的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换.

但如果我用"一切正常"来包装价值:

{"Sex" : '0'}
Run Code Online (Sandbox Code Playgroud)

有人有同样的问题吗?

Tnx为所有人!

小智 6

是的,我遇到了同样的问题.奇怪的问题是,如果你发回:

{"Sex" : 'Male'}
Run Code Online (Sandbox Code Playgroud)

它会反序列化没问题.为了解决这个问题,我为枚举实现了一个自定义模型绑定器,利用了这里的例子(稍微修改了一些错误):http: //eliasbland.wordpress.com/2009/08/08/enumeration-model-binder -用于-ASP净MVC /

namespace yournamespace
{
    /// <summary>
    /// Generic Custom Model Binder used to properly interpret int representation of enum types from JSON deserialization, including default values
    /// </summary>
    /// <typeparam name="T">The enum type to apply this Custom Model Binder to</typeparam>
    public class EnumBinder<T> : IModelBinder
    {
        private T DefaultValue { get; set; }

        public EnumBinder(T defaultValue)
        {
            DefaultValue = defaultValue;
        }

        #region IModelBinder Members
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            return bindingContext.ValueProvider.GetValue(bindingContext.ModelName) == null ? DefaultValue : GetEnumValue(DefaultValue, bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue);
        }
        #endregion

        public static T GetEnumValue<T>(T defaultValue, string value)
        {
            T enumType = defaultValue;

            if ((!String.IsNullOrEmpty(value)) && (Contains(typeof(T), value)))
                enumType = (T)Enum.Parse(typeof(T), value, true);

            return enumType;
        }

        public static bool Contains(Type enumType, string value)
        {
            return Enum.GetNames(enumType).Contains(value, StringComparer.OrdinalIgnoreCase);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在global.asax.cs中注册模型绑定器.在你的情况下,它将是这样的:

ModelBinders.Binders.Add(typeof(SexType), new EnumBinder<SexType>(SexType.Male));
Run Code Online (Sandbox Code Playgroud)

我不确定是否有更快的方法,但这很有效.