Recipe 11.6. 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 web part described in Recipe 11.4, as shown below. With this addition, the book category the user last selected is preselected for her on subsequent requests for the page.

 

<Personalizable( )> _ Public Property BookCategory( ) As String _ Implements IBookCategoryVB.BookCategory Get 'make sure the child controls have been created EnsureChildControls( ) Return (ddBookCategories.SelectedValue) End Get Set(ByVal value As String) 'make sure the child controls have been created EnsureChildControls( ) 'find the item matching the passed value in the drop down list 'and select it ddBookCategories.SelectedIndex = _ ddBookCategories.Items.IndexOf(ddBookCategories.Items.FindByValue(value)) End Set End Property

[Personalizable( )] public String BookCategory { get { // make sure the child controls have been created EnsureChildControls( ); return (ddBookCategories.SelectedValue); } set { // make sure the child controls have been created EnsureChildControls( ); // find the item matching the passed value in the drop down list // and select it ddBookCategories.SelectedIndex = ddBookCategories.Items.IndexOf(ddBookCategories.Items.FindByValue(value)); } }

Storing custom property data for your web parts is a great way to enhance the user experience for your application.

See Also

Recipe 11.4



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net