What is the difference between BindProperty and SetProperty on IModelBinder

前端 未结 2 468
长情又很酷
长情又很酷 2021-02-13 21:17

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 overrid

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-13 22:09

    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.

提交回复
热议问题