views:

204

answers:

1

I'm creating a custom model binder in an Mvc application and I want to parse a string to an enumeration value and assign it to the model property. I have got it working overriding the BindProperty method, but I also noticed that there is a SetProperty method.

    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
    {
        switch (propertyDescriptor.Name)
        {
            case "EnumProperty":
                BindEnumProperty(controllerContext, bindingContext);
                break;
        }

        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }

    private static void BindEnumProperty(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var formValue = controllerContext.HttpContext.Request.Form["formValue"];

        if (String.IsNullOrEmpty(formValue))
        {
            throw new ArgumentException();
        }

        var model = (MyModel)bindingContext.Model;
        model.EnumProperty = (EnumType)Enum.Parse(typeof(EnumType), formValue);
    }

I’m not sure what the difference is between the two and whether I am doing this in the recommended way.

A: 

I think SetProperty takes actual value to set as the last parameter.

Jakub Konecki