What is the difference between BindProperty and SetProperty on IModelBinder
Asked Answered
P

2

12

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.

Panfish answered 11/2, 2010 at 15:51 Comment(0)
P
8

First of all, BindProperty is not a part of IModelBinder but, a protected method in DefaultModelBinder. You can access it only if you are sub-classing the DefaultModelBinder.

The following points should answer your question:

  • BindProperty uses the IModelBinder interface it gets from the PropertyType of the propertyDescriptor argument. This allows you to inject custom properties into the property metadata.
  • BindProperty properly handles validation. It (also) calls the SetProperty method only if the new value is valid.

So if you want proper validation (using the annotation attributes) you must definitely call BindProperty. By calling SetProperty you bypass all the built-in validation mechanisms.

You should check out the source code of DefaultModelBinder the see what each method does, since the intellisense provides only limited information.

Pap answered 25/11, 2010 at 9:56 Comment(3)
Source is now at aspnetwebstack.codeplex.com/SourceControl/latest#src/…Cancroid
@Cancroid Your URL is invalid alsoMcdaniels
@Kilanny, invalid how? It still seems to work for me.Cancroid
C
0

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

Cognomen answered 29/9, 2010 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.