Custom model binder for a property

前端 未结 4 1257
遇见更好的自我
遇见更好的自我 2020-11-30 04:08

I have the following controller action:

[HttpPost]
public ViewResult DoSomething(MyModel model)
{
    // do something
    return View();
}

4条回答
  •  一个人的身影
    2020-11-30 04:18

    @jonathanconway's answer is great, but I would like to add a minor detail.

    It's probably better to override the GetPropertyValue method instead of BindProperty in order to give the validation mechanism of the DefaultBinder a chance to work.

    protected override object GetPropertyValue(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext,
        PropertyDescriptor propertyDescriptor,
        IModelBinder propertyBinder)
    {
        PropertyBinderAttribute propertyBinderAttribute =
            TryFindPropertyBinderAttribute(propertyDescriptor);
        if (propertyBinderAttribute != null)
        {
            propertyBinder = CreateBinder(propertyBinderAttribute);
        }
    
        return base.GetPropertyValue(
            controllerContext,
            bindingContext,
            propertyDescriptor,
            propertyBinder);
    }
    

提交回复
热议问题