Using private property setters with the MVC CSLA Model Binder

Using private property setters with the MVC CSLA Model Binder

Old forum URL: forums.lhotka.net/forums/t/11571.aspx


nickh posted on Tuesday, September 11, 2012

Hi all,

 

I've read through Rocky's "Using CSLA 4 with ASP.NET MVC" ebook and have implemented the methodologies suggested by him, including the use of the CSLA Model Binder, but this has lead me to an interesting problem...

Some class properties within my business layer have private setters (adopting a LoadProperty approach).  This results in the empty property values coming through into my controller, when the CSLA Model Binder tries to construct the object.

I presume that this is a known issue?  How should I go about resolving it?

Thanks,

 

Nick

JonnyBee replied on Tuesday, September 11, 2012

The modelbinder will use the property setter so if you want these to be updated by the modelbinder you must make them public.

Or - you can create your own ModelBinder class that inherits from CslaModelBinder in your app and add override CreateModel to add special handling for these properties.

nickh replied on Tuesday, September 11, 2012

Hi Jonny,

Thanks for your reply.

I do not want to expose the properties via a public setter.  I already have a CreateModel method in my controller (to avoid a private constructor issue), so exactly how do I go about extending this method to add "special handling" for certain properties?

 

Nick

JonnyBee replied on Tuesday, September 11, 2012

  1. Make the PropertyInfos public in scope
  2. If you use private backing fields you must override the non-generic LoadProperty in your BO
    Only BO should know about the private member variables.
  3. Create an "accessor" class that inherits from ObjectFactory and exposes LoadProperty
  4. Call accessor.LoadProperty(obj, PropertyInfo, value) to load properties into backing fields.

Sample ModelAccessor class:

 

  public class ModelAccessor : Csla.Server.ObjectFactory

  {

    public new void LoadProperty(object obj, IPropertyInfo propertyInfo, object newValue)

    {

      base.LoadProperty(obj, propertyInfo, newValue);

    }

  }

 

Copyright (c) Marimer LLC