Using non serializable properties with WebParts 

Tags:

Just recently I was working with a member of our team debugging an issue with one of our custom WebParts. We were exposing a property value as an object which is allowable via both the WebPart and WebControl classes using a declaration similar to the following:

[Browsable(false)]
public
object WebPartObject
{
  
get { return this.member_varible; }
  
set { this.member_varible = value; }
}

Once we published with WebPart to our SharePoint site everything appeared to work as planned until we started to use the control and handled a few post backs at which time we noticed that our Title value was getting overwritten to a blank value and shown as untitled on the WebPart page. With little further research we uncovered that it was an issue with the WebPart serialization of the property. Since the object we were storing was not serialzable it caused issues with the storage WebPart storage model.

With that we had to figure out a way to expose the object but exclude it from the WebPart storage model and of course it was a quite a simple solution. The trick is to add a WebPartStorage property declaration which is commonly set to Shared or Personal. Since the variable should not be stored as part of the WebPart serialization we can tell SharePoint to ignore the value by setting the attribute to None. So end the end we ended up with the following declaration which worked great.

[Browsable(false)]
[WebPartStorage(Storage.None)]
public
object WebPartObject
{
  
get { return this.member_varible; }
  
set { this.member_varible = value; }
}

Not rocket science but a nice little tidbit to know when you are adding properties to your WebParts.

 
Posted by Malcolm Hyson on 4-Sep-08
222 Comments  |  Trackback Url  |  Link to this post | Bookmark this post with:        
 

Links to this post

Comments

Name:
URL:
Email:
Comments: