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, 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;
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With