PropertyDescriptor.SetValue在ModelBinder中不起作用

本文关键字:不起作用 ModelBinder SetValue PropertyDescriptor | 更新日期: 2023-09-27 18:01:18

我正在实现一个自定义的ModelBinder,我试图用PropertyDescriptor设置属性。SetValue和我不知道为什么它不工作。

对于一些复杂的属性,值没有被设置,但它不会抛出异常。属性仍然是null,但对于某些属性,它确实是。

如果我检索PropertyInfo并调用SetValue,它每次都能很好地工作。

Mvc源代码从codeplex内部使用propertyDescriptor.SetValue(bindingContext.Model, value);所以我猜这是最好的方式去?

public class MyCustomBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(bindingContext.Model))
            {
                object value = property.GetValue(bindingContext.Model);
                // Perform custom bindings
                // Call SetValue on PropertyDescriptor (Works sometimes)
                property.SetValue(bindingContext.Model, value);
                Debug.Assert(property.GetValue(bindingContext.Model) == value, "Value not set");
                // Get PropertyInfo and call SetValue (Working)                    
                bindingContext.ModelType.GetProperty(property.Name).SetValue(bindingContext.Model, value, null);
                Debug.Assert(property.GetValue(bindingContext.Model) == value, "Value not set");
            }
            return bindingContext.Model;
        }
    }

注意1:我反射的对象是用nhibernate映射的,所以我怀疑代理可能有问题。

注意2:它也不能与DefaultModelBinder一起工作,但是对象正在被重新创建,因此发布的数据很好。

PropertyDescriptor.SetValue在ModelBinder中不起作用

我不确定您想要实现什么,但我会忽略MVC源代码使用propertyDescriptor的事实。SetValue,如果你已经知道propertyInfo。setValue给你你想要的。你正在编写一个扩展类,只使用工作和良好的代码:

Type modelType = bindingContext.ModelType;
foreach (PropertyInfo property in modelType.GetProperties())
{
    // ...
    property.SetValue(bindingContext.Model, value, null);
}