Mvc binding error from json to enum (customexception from int to listing)

I have this problem: I use json to send data to the server. Everything works fine, but the problem is in a situation like:

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

class People{
  public SexType Sex {get;set;}
}

This will create me json:

{"Sex" : 0}

When I get back to the server, fill out this model: ModelStateError: The conversion of the parameters from the type "System.Int32" to the type "SexType" failed because the type converter cannot convert between these types.

But if I wrap the value "everything works well:

{"Sex" : '0'}

Does anyone have the same problem?

Tnx for everyone!

+3
source share
2 answers

Yes, I have the same problem. The strange problem is that if you sent back:

{"Sex" : 'Male'}

. , , , ( , ): http://eliasbland.wordpress.com/2009/08/08/enumeration-model-binder-for-asp-net-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);
        }
    }
}

global.asax.cs. - :

ModelBinders.Binders.Add(typeof(SexType), new EnumBinder<SexType>(SexType.Male));

, , .

+6

Model Enum.Parse(), , , , , Enum.

? , , , Enum , , Enum Enum.

( , , , ) , , .. , "", "" , eg IsFemale true false. json, , , , .

+2

Source: https://habr.com/ru/post/1792549/


All Articles