Some notes on software development... RSS 2.0
# Wednesday, 06 June 2012

This post is an extension to How to Bind to Enums on JSON Objects in ASP.NET MVC 3 from www.codetunnel.com so please see that excellent post for more details.
This class basically extends the MVC default model binder to include Enum property support. This allows models with enum properties to be correctly set (bound) when JSON is sent to the controllers action method.

The class is nearly identical to codetunnel’s version, I just included the Enum.Parse statement so that it also supports enum name values being passed in.

 

So the class looks like this:

    public class DefaultModelBinderEx : 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 (providerValue != null)
                {
                    var value = providerValue.RawValue;

                    if (value != null)
                    {
                        var valueType = value.GetType();

                        if (valueType == typeof(string[]))
                        {
                            valueType = typeof(string);
                            value = ((string[])value)[0];
                        }

                        if (!valueType.IsEnum)
                        {
                            return Enum.Parse(propertyType, value.ToString());
                        }
                    }
                }
            }

            return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
        }
    }

..and then you just need to update the Application_Start method in the Global.asax file with this line:

ModelBinders.Binders.DefaultBinder = new U413ModelBinder();

Now your default binding will support models with Enum properties.

Wednesday, 06 June 2012 13:20:35 (GMT Standard Time, UTC+00:00)  #    -
ASP.NET MVC
Navigation

Sign In
Extras
Statistics
Total Posts: 116
This Year: 0
This Month: 0
This Week: 0
Comments: 36
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2018
Hadrian Phillips

All Content © 2018, Hadrian Phillips
DasBlog theme 'Business' created by Christoph De Baene (delarou)