12

我正在 Mvc 应用程序中创建自定义模型绑定器,我想将字符串解析为枚举值并将其分配给模型属性。我已经让它覆盖了该BindProperty方法,但我也注意到有一个SetProperty方法。

    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);
    }

我不确定两者之间有什么区别以及我是否以推荐的方式这样做。

4

2 回答 2

8

首先,BindProperty 不是 IModelBinder 的一部分,而是 DefaultModelBinder 中受保护的方法。只有在继承 DefaultModelBinder 时才能访问它。

以下几点应该可以回答您的问题:

  • BindProperty 使用从 propertyDescriptor 参数的 PropertyType 获取的 IModelBinder 接口。这允许您将自定义属性注入到属性元数据中。
  • BindProperty 正确处理验证。它(也)仅在新值有效时才调用 SetProperty 方法。

所以如果你想要正确的验证(使用注解属性)你必须调用 BindProperty。通过调用 SetProperty,您可以绕过所有内置的验证机制。

您应该查看DefaultModelBinder的源代码,了解每个方法的作用,因为智能感知仅提供有限的信息。

于 2010-11-25T09:56:07.860 回答
0

我认为 SetProperty 将实际值设置为最后一个参数。

于 2010-09-29T21:08:25.750 回答