开发者

PropertyDescriptor.SetValue not working in ModelBinder

开发者 https://www.devze.com 2023-03-18 07:13 出处:网络
I\'m implementing a custom ModelBinder where I\'m trying to set a property with PropertyDescriptor.SetValue and I can\'t figure out why it isn\'t working.

I'm implementing a custom ModelBinder where I'm trying to set a property with PropertyDescriptor.SetValue and I can't figure out why it isn't working.

For some complex properties the value isn't being set but it doesn't throw an exception. The property is still null but for some it does.

If i retrieve a PropertyInfo and call SetValue it works just fine every time.

The Mvc source from codeplex is using propertyDescriptor.SetValue(bindingContext.Model, value); internally so I'm guessing it's the best way to go?

public class MyCustomBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingCont开发者_开发百科ext 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;
        }
    }

Note 1: The objects im reflecting upon is mapped with nhibernate so I'm suspecting there might be something with the proxies.

Note 2: It isn't working with the DefaultModelBinder either but the objects are being recreated so the posted data is fine.


I am not sure what you want to achieve, but I would ignore the fact that the MVC source code uses propertyDescriptor.SetValue, if you already know that propertyInfo.setValue gives you what you want. You are writing an extension class, just use what works and is good code:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号