11.5. Persisting Personalized Web Part Properties

Problem

You have created a web part with custom properties and you want the property data to be persisted along with the other web part personalization data so the next time the user revisits the page, his property settings are present.

Solution

Decorate the properties in your web part that you want persisted with the Personalizable attribute:


	<Personalizable( )> _
	Public Property BookCategory( ) As String
		Get

			…

		End Get

		Set(ByVal value As String)

			…

		End Set
	End Property


	[Personalizable( )]
	public String BookCategory
	{
		get
		{
			…
		}

		set
		{
			…
		}
	}

Discussion

The web part infrastructure automatically handles persisting the personalization performed by the user when he adds web parts to pages. Which web parts the user selected and their location on the page is automatically stored and retrieved when the user revisits your site. You do not have to write any code to make this happen.

Adding custom property data to the persisted data is straightforward and requires only a small modification to your code. You will need to add the Personalizable attribute to each of the properties you want persisted. No other modifications are required.

To demonstrate this technique, we added the Personalizable attribute to the BookCategory property of the book category ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.