Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace U413.UI.CustomModelBinders
- {
- /// <summary>
- /// Override for DefaultModelBinder in order to implement fixes to its behavior.
- /// </summary>
- public class U413ModelBinder : 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);
- }
- }
- }
- protected override void OnApplicationStarted()
- {
- base.OnApplicationStarted();
- AreaRegistration.RegisterAllAreas();
- RegisterRoutes(RouteTable.Routes);
- // Register your new model binder
- ModelBinders.Binders.DefaultBinder = new U413ModelBinder();
- }
- public class SomeModel
- {
- public MyEnum EnumValue { get; set; }
- public int BindToThisGuy
- {
- get { return (int) EnumValue; }
- set { EnumValue = (MyEnum)value; }
- }
- }
- namespace MyApp.Enums
- {
- public enum ATS_Tabs { TabOne = 0, TabTwo = 1, TabThree = 2, TabFour = 3, TabFive = 4 };
- public class ModelEnums
- {
- public static IEnumerable<Type> Types
- {
- get
- {
- List<Type> Types = new List<Type>();
- Types.Add(typeof(ATS_Tabs));
- return Types;
- }
- }
- }
- }
- namespace MyApp.CustomModelBinders
- {
- public class EnumModelBinder : IModelBinder
- {
- public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
- {
- ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
- ModelState modelState = new ModelState { Value = valueResult };
- object actualValue = null;
- try
- {
- return Enum.ToObject(Type.GetType(bindingContext.ModelType.AssemblyQualifiedName), Convert.ToInt32(valueResult.AttemptedValue));
- }
- catch (FormatException e)
- {
- modelState.Errors.Add(e);
- }
- bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
- return actualValue;
- }
- }
- }
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- foreach (Type type in ModelEnums.Types)
- {
- ModelBinders.Binders.Add(type, new EnumModelBinder());
- }
- RegisterGlobalFilters(GlobalFilters.Filters);
- RegisterRoutes(RouteTable.Routes);
- }
Add Comment
Please, Sign In to add comment