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!
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));
, , .
Model Enum.Parse(), , , , , Enum.
? , , , Enum , , Enum Enum.
( , , , ) , , .. , "", "" , eg IsFemale true false. json, , , , .
Source: https://habr.com/ru/post/1792549/More articles:'undefined' appears in the message - javascriptHow to make haskell not store whole bytes? - optimizationTesting Entity Framework 3.5 - c #есть генератор синтаксического анализатора, способный генерировать парсер, который может анализировать это: S → 'x' S 'x'Closure Compiler Completion - Any Performance Hits? - performanceWhat correct configuration line should be designed, omniauth and google work? - ruby-on-railsHow to run and debug a C ++ application in Eclipse that started with a script? - c ++AccessViolationException from System.Windows.Forms using WinFormsHost in WPF - c #Dataset - Unable to read XML 1.1? - c #WPF StackPanel.Resources setter for multiple control types? - c #All Articles