Walkthrough: Creating a Web Parts Page
This walkthrough is a hands-on demonstration of the essential components and tasks for creating Web pages that use Web Parts controls.
In many Web applications it is useful to allow users to select and arrange the content they want to see. The ASP.NET Web Parts feature consists of a set of controls for creating Web pages that present modular content, and that enable users to change the appearance and content to suit their preferences. For a general introduction to Web Parts, see ASP.NET Web Parts Overview. For a description of the main components in the Web Parts control set, several of which are used in this walkthrough, see Web Parts Control Set Overview.
During this walkthrough, you use Web Parts controls to create a Web page that users can modify, or personalize. Tasks illustrated in this walkthrough include:
Adding Web Parts controls to a page.
Creating a custom user control and using it as a Web Parts control.
Enabling users to personalize the layout of the Web Parts controls on the page.
Enabling users to edit the appearance of a Web Parts control.
Enabling users to select from a catalog of available Web Parts controls.
Prerequisites
In order to complete this walkthrough, you will need:
Internet Information Services (IIS) installed and configured on the computer that will host the site. For details about installing and configuring IIS, see the IIS Help documentation included with the installation, or see the online IIS documentation on the Microsoft TechNet site (Internet Information Services 6.0 Technical Resources).
An ASP.NET Web site that can identify individual users. If you have such a site already configured, you can use that site as a starting point for this walkthrough. Otherwise, for details on creating a virtual directory or site, see How to: Create and Configure Virtual Directories in IIS or How to: Create and Configure Local ASP.NET Web Sites in IIS.
A configured personalization provider and database. Web Parts personalization is enabled by default, and it uses the SQL personalization provider (SqlPersonalizationProvider) with the Microsoft SQL Server Standard Edition to store personalization data. This walkthrough uses SSE and the default SQL provider. If you have SSE installed, no configuration is needed. SSE is available with Microsoft Visual Studio 2005 as an optional part of the installation, or as a free download. For details, see the Microsoft SQL Server 2005 Express Edition Web page. To use one of the full versions of SQL Server, you must install and configure an ASP.NET application services database, and configure the SQL personalization provider to connect to that database. For details, see Creating and Configuring the Application Services Database for SQL Server. You can also create and configure a custom provider to use with other, non-SQL databases or storage solutions. For details and a code example see Implementing a Membership Provider.
Creating a Simple Page with Web Parts
In this part of the walkthrough, you create a page that uses Web Parts to show static content.
Note |
---|
You do not need to do anything to enable Web Parts personalization; it is enabled by default for the Web Parts control set. When you first run a Web Parts page on a site, ASP.NET sets up a default personalization provider to store user personalization settings. The default provider uses a database created in a subdirectory of your site's directory. For more information about personalization, see Web Parts Personalization Overview. |
To create a Web page
In your text editor, create a new file and add the following page declaration to the beginning of the file.
<%@ page language="VB" %>
<%@ page language="C#" %>
Enter tags beneath the page declaration to create a complete page structure as shown in the following code example.
Note that the page includes an empty table with one row and three columns. The table will contain the Web Parts controls you will add later.
<html> <head runat="server"> <title>Web Parts Page</title> </head> <body> <h1>Web Parts Demonstration Page</h1> <form runat="server" id="form1"> <br /> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td valign="top"> </td> <td valign="top"> </td> <td valign="top"> </td> </tr> </table> </form> </body> </html>
Name the file
WebPartsDemo.aspx
, and save it in the directory for your Web site.
The next step is to set up zones. Zones are composite controls that occupy a specified region of a page and contain Web Parts controls.
To add zones to the page
Just below the <form> element in your page, add an <asp:webpartmanager> element, as shown in the following example.
<asp:webpartmanager id="WebPartManager1" runat="server" />
The WebPartManager control is required on every page that uses Web Parts controls.
Add an <asp:webpartzone> element inside the first <td> element in the table, and assign its property values as shown in the following code example.
Note that the <asp:webpartzone> element also contains a <zonetemplate> element. The Web Parts controls are placed within the <zonetemplate> element.
<table cellspacing="0" cellpadding="0" border="0"> <tr> <td valign="top"> <asp:webpartzone id="SideBarZone" runat="server" headertext="Sidebar"> <zonetemplate> </zonetemplate> </asp:webpartzone> </td>
Add an <asp:webpartzone> element inside the second <td> element in the table, and assign its property values as shown in the following code example:
<td valign="top"> <asp:webpartzone id="MainZone" runat="server" headertext="Main"> <zonetemplate> </zonetemplate> </asp:webpartzone> </td>
Save the
WebPartsDemo.aspx
file.
Your page now has two zones that you can control separately. However, neither zone has any content, so the next step is to create content. For this walkthrough, you work with Web Parts controls that display only static content.
The layout of the Web Parts zone is specified by a <zonetemplate> element. Inside the zone template, you can add any Web server control, whether it is a custom Web Parts control, a user control, or an existing server control. In this walkthrough you are using the Label server control, and inside it you are simply adding static text. When you place a regular ASP.NET server control in a WebPartZone zone, ASP.NET treats it as a Web Parts control at run time, which enables you to use most Web Parts features with standard server controls.
To create content for the zones
Inside the <zonetemplate> element for the
Main
zone, add an <asp:label> element with some content, as shown in the following code example:<asp:webpartzone id="MainZone" runat="server" headertext="Main"> <zonetemplate> <asp:label id="contentPart" runat="server" title="Content"> <h2>Welcome to My Home Page</h2> <p>Use links to visit my favorite sites!</p> </asp:label> </zonetemplate> </asp:webpartzone>
Save the
WebPartsDemo.aspx
file.Create a new file in your text editor.
This file will contain a user control that can also be added to the page as a Web Parts control.
At the top of the new file, add a control declaration as shown in the following example.
<%@ control language="VB" classname="SearchUserControl" %>
<%@ control language="C#" classname="SearchUserControl" %>
Note The search control for this walkthrough does not implement actual search functionality; it is used only to demonstrate Web Parts features.
Beneath the control declaration, add a pair of <script> tags, and within them add code to create a personalizable property.
Note that the
ResultsPerPage
property has a Personalizable attribute. This property would enable users of the control to personalize how many search results to return per page, if you provided an edit control with the user interface (UI) to change the setting in Design view.Make sure the code for your control looks like the following code example:
<%@ control language="VB" classname="SearchUserControl" %> <script runat="server"> Private results As Integer <Personalizable()> _ Property ResultsPerPage() As Integer Get Return results End Get Set(ByVal value As Integer) results = value End Set End Property </script>
<%@ control language="C#" classname="SearchUserControl" %> <script runat="server"> private int results; [Personalizable] public int ResultsPerPage { get {return results;} set {results = value;} } </script>
Add a text box and a button below the <script> element to provide the UI for a search control, as shown in the following code example:
<asp:textbox runat="server" id="inputBox"></asp:textbox> <br /> <asp:button runat="server" id="searchButton" text="Search" />
Security Note This control has a textbox that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate user input to ensure that the input does not contain HTML elements or script. For more information, see Script Exploits Overview.
Name the file
SearchUserControlVB.ascx
orSearchUserControlCS.ascx
(depending on which language you are using), and save it in the same directory as theWebPartsDemo.aspx
page.
Now you will add two controls to the Sidebar
zone, one containing a list of links and another that is the user control you created in the previous procedure. The links are added as a single, standard Label server control, similar to the way you created the static text for the Main
zone. However, although the individual server controls contained in the user control could be contained directly in the zone, in this case they are not. Instead, they are part of the user control you created in the previous procedure. This demonstrates a common way to package whatever controls and extra functionality you want in a user control, and then reference that user control in a zone as a Web Parts control.
At run time, ASP.NET wraps both controls with GenericWebPart controls. When a GenericWebPart control wraps a Web server control, the generic part control is the parent, and you can access the server control through the parent control's ChildControl property. Generic part controls enable standard Web server controls to have the same basic behavior and attributes as Web Parts controls that derive from the WebPart class.
To create content for the Sidebar zone
Open the
WebPartsDemo.aspx
page in your text editor.At the top of the page, just after the page declaration, add the following declaration to reference the user control you just created:
<%@ register tagprefix="uc1" tagname="SearchUserControl" src="searchusercontrolvb.ascx" %>
<%@ register tagprefix="uc1" tagname="SearchUserControl" src="searchusercontrolcs.ascx" %>
Inside the <zonetemplate> element for the
Sidebar
zone, add a Label control containing several links. Beneath the control, reference the user control you created previously, as shown in the following code example:<asp:webPartZone id="SidebarZone" runat="server" headertext="Sidebar"> <zonetemplate> <asp:label runat="server" id="linksPart" title="Links"> <a href="www.asp.net">ASP.NET site</a> <br /> <a href="www.gotdotnet.com">GotDotNet</a> <br /> <a href="www.contoso.com">Contoso.com</a> <br /> </asp:label> <uc1:SearchUserControl id="searchPart" runat="server" title="Search" /> </zonetemplate> </asp:WebPartZone>
Save the
WebPartsDemo.asp
x file.
Now you can test your page.
To test the page
Load the page in a browser.
The page displays the two zones. Each control on the page is displayed with a downward arrow in its title bar, which contains a drop-down menu called the verbs menu. Verbs are actions that a user can carry out on a server control, such as closing, minimizing, or editing a control. Each item in the verbs menu is a verb. The following screen shot shows the page.
Click the downward arrow in a control's title bar to display its verbs menu, and then click the Minimize link.
The control is minimized.
In the verbs menu, click Restore.
This demonstrates the different visual display states of Web Parts controls.
Enabling Users to Edit Pages and Change Layout
Users can change the layout of Web Parts controls by dragging them from one zone to another. You can also enable users to edit control characteristics such as appearance, layout, and behavior. The Web Parts control set provides basic editing functionality for WebPart controls. (Although you will not do so in this walkthrough, you can also create custom editor controls that enable users to edit the features of WebPart controls.) As with changing the location of a WebPart control, editing its properties relies on ASP.NET personalization to save the changes that users make.
In this part of the walkthrough, you enable users to edit the basic characteristics of any WebPart control on the page.
To create a user control that enables changing page layout
Create a new file in your text editor and copy in the following code.
This code uses features of the Web Parts control set that enable a page to change its view or display mode. It also enables you to change the physical appearance and layout of the page while you are in certain display modes.
<%@ control language="vb" classname="DisplayModeMenuVB"%> <script runat="server"> ' Use a field to reference the current WebPartManager control. Dim _manager As WebPartManager Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) AddHandler Page.InitComplete, AddressOf InitComplete End Sub Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs) _manager = WebPartManager.GetCurrentWebPartManager(Page) Dim browseModeName As String = _ WebPartManager.BrowseDisplayMode.Name ' Fill the drop-down list with the names of supported display modes. Dim mode As WebPartDisplayMode For Each mode In _manager.SupportedDisplayModes Dim modeName As String = mode.Name ' Make sure a mode is enabled before adding it. If mode.IsEnabled(_manager) Then Dim item As New ListItem(modeName, modeName) DisplayModeDropdown.Items.Add(item) End If Next mode ' If Shared scope is allowed for this user, display the ' scope-switching UI and select the appropriate radio button ' for the current user scope. If _manager.Personalization.CanEnterSharedScope Then Panel2.Visible = True If _manager.Personalization.Scope = _ PersonalizationScope.User Then RadioButton1.Checked = True Else RadioButton2.Checked = True End If End If End Sub ' Change the page to the selected display mode. Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, _ ByVal e As EventArgs) Dim selectedMode As String = DisplayModeDropdown.SelectedValue Dim mode As WebPartDisplayMode = _ _manager.SupportedDisplayModes(selectedMode) If Not (mode Is Nothing) Then _manager.DisplayMode = mode End If End Sub ' Set the selected item equal to the current display mode. Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs) Dim items As ListItemCollection = DisplayModeDropdown.Items Dim selectedIndex As Integer = _ items.IndexOf(items.FindByText(_manager.DisplayMode.Name)) DisplayModeDropdown.SelectedIndex = selectedIndex End Sub ' Reset all of a user's personalization data for the page. Protected Sub LinkButton1_Click(ByVal sender As Object, _ ByVal e As EventArgs) _manager.Personalization.ResetPersonalizationState() End Sub ' If not in User personalization scope, toggle into it. Protected Sub RadioButton1_CheckedChanged(ByVal sender As _ Object, ByVal e As EventArgs) If _manager.Personalization.Scope = _ PersonalizationScope.Shared Then _manager.Personalization.ToggleScope() End If End Sub ' If not in Shared scope, and if user has permission, toggle the ' scope. Protected Sub RadioButton2_CheckedChanged(ByVal sender As _ Object, ByVal e As EventArgs) If _manager.Personalization.CanEnterSharedScope AndAlso _ _manager.Personalization.Scope = _ PersonalizationScope.User Then _manager.Personalization.ToggleScope() End If End Sub </script> <div> <asp:Panel ID="Panel1" runat="server" Borderwidth="1" Width="230" BackColor="lightgray" Font-Names="Verdana, Arial, Sans Serif" > <asp:Label ID="Label1" runat="server" Text=" Display Mode" Font-Bold="true" Font-Size="8" Width="120" /> <div> <asp:DropDownList ID="DisplayModeDropdown" runat="server" AutoPostBack="true" Width="120" OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" /> <asp:LinkButton ID="LinkButton1" runat="server" Text="Reset User State" ToolTip="Reset the current user's personalization data for the page." Font-Size="8" OnClick="LinkButton1_Click" /> </div> <asp:Panel ID="Panel2" runat="server" GroupingText="Personalization Scope" Font-Bold="true" Font-Size="8" Visible="false" > <asp:RadioButton ID="RadioButton1" runat="server" Text="User" AutoPostBack="true" GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" /> <asp:RadioButton ID="RadioButton2" runat="server" Text="Shared" AutoPostBack="true" GroupName="Scope" OnCheckedChanged="RadioButton2_CheckedChanged" /> </asp:Panel> </asp:Panel> </div>
<%@ control language="C#" classname="DisplayModeMenuCS"%> <script runat="server"> // Use a field to reference the current WebPartManager control. WebPartManager _manager; void Page_Init(object sender, EventArgs e) { Page.InitComplete += new EventHandler(InitComplete); } void InitComplete(object sender, System.EventArgs e) { _manager = WebPartManager.GetCurrentWebPartManager(Page); String browseModeName = WebPartManager.BrowseDisplayMode.Name; // Fill the drop-down list with the names of supported display modes. foreach (WebPartDisplayMode mode in _manager.SupportedDisplayModes) { String modeName = mode.Name; // Make sure a mode is enabled before adding it. if (mode.IsEnabled(_manager)) { ListItem item = new ListItem(modeName, modeName); DisplayModeDropdown.Items.Add(item); } } // If Shared scope is allowed for this user, display the // scope-switching UI and select the appropriate radio // button for the current user scope. if (_manager.Personalization.CanEnterSharedScope) { Panel2.Visible = true; if (_manager.Personalization.Scope == PersonalizationScope.User) RadioButton1.Checked = true; else RadioButton2.Checked = true; } } // Change the page to the selected display mode. void DisplayModeDropdown_SelectedIndexChanged(object sender, EventArgs e) { String selectedMode = DisplayModeDropdown.SelectedValue; WebPartDisplayMode mode = _manager.SupportedDisplayModes[selectedMode]; if (mode != null) _manager.DisplayMode = mode; } // Set the selected item equal to the current display mode. void Page_PreRender(object sender, EventArgs e) { ListItemCollection items = DisplayModeDropdown.Items; int selectedIndex = items.IndexOf(items.FindByText(_manager.DisplayMode.Name)); DisplayModeDropdown.SelectedIndex = selectedIndex; } // Reset all of a user's personalization data for the page. protected void LinkButton1_Click(object sender, EventArgs e) { _manager.Personalization.ResetPersonalizationState(); } // If not in User personalization scope, toggle into it. protected void RadioButton1_CheckedChanged(object sender, EventArgs e) { if (_manager.Personalization.Scope == PersonalizationScope.Shared) _manager.Personalization.ToggleScope(); } // If not in Shared scope, and if user has permission, toggle // the scope. protected void RadioButton2_CheckedChanged(object sender, EventArgs e) { if (_manager.Personalization.CanEnterSharedScope && _manager.Personalization.Scope == PersonalizationScope.User) _manager.Personalization.ToggleScope(); } </script> <div> <asp:Panel ID="Panel1" runat="server" Borderwidth="1" Width="230" BackColor="lightgray" Font-Names="Verdana, Arial, Sans Serif" > <asp:Label ID="Label1" runat="server" Text=" Display Mode" Font-Bold="true" Font-Size="8" Width="120" /> <div> <asp:DropDownList ID="DisplayModeDropdown" runat="server" AutoPostBack="true" Width="120" OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" /> <asp:LinkButton ID="LinkButton1" runat="server" Text="Reset User State" ToolTip="Reset the current user's personalization data for the page." Font-Size="8" OnClick="LinkButton1_Click" /> </div> <asp:Panel ID="Panel2" runat="server" GroupingText="Personalization Scope" Font-Bold="true" Font-Size="8" Visible="false" > <asp:RadioButton ID="RadioButton1" runat="server" Text="User" AutoPostBack="true" GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" /> <asp:RadioButton ID="RadioButton2" runat="server" Text="Shared" AutoPostBack="true" GroupName="Scope" OnCheckedChanged="RadioButton2_CheckedChanged" /> </asp:Panel> </asp:Panel> </div>
Name the file
Displaymodemenu.ascx
and save it in the directory you used for the other pages.
To enable users to change the layout
In the
WebPartsDemo.aspx
page, add a <register> directive to register the new user control on the page:<%@ register TagPrefix="uc2" TagName="DisplayModeMenuVB" Src="DisplayModeMenu.ascx" %>
<%@ register TagPrefix="uc2" TagName="DisplayModeMenuCS" Src="DisplayModeMenu.ascx" %>
Add a declarative reference to the user control immediately below the <asp:webpartmanager> element:
<uc2:DisplayModeMenuVB ID="DisplayModeMenu1" runat="server" />
<uc2:DisplayModeMenuCS ID="DisplayModeMenu1" runat="server" />
Add an <asp:editorzone> element inside the third <td> element in the table. Add a <zonetemplate> element, an <asp:appearanceeditorpart> element, and an <asp:layouteditorpart> element.
When you are done, the code will look like the following example:
<td valign="top"> <asp:editorzone id="EditorZone1" runat="server"> <zonetemplate> <asp:appearanceeditorpart runat="server" id="AppearanceEditorPart1" /> <asp:layouteditorpart runat="server" id="LayoutEditorPart1" /> </zonetemplate> </asp:editorzone> </td>
Note Two additional controls, the BehaviorEditorPart and PropertyGridEditorPart controls, are not used because they require setup beyond the scope of this walkthrough.
Save the
WebPartsDemo.aspx
file.You have created a user control that enables you to change display modes and change page layout, and you have referenced the control on the primary Web page.
You can now test the capability to edit pages and change layout.
To test layout changes
Load the page in a browser.
Click the Display Mode drop-down menu, and then select Edit.
The zone titles are displayed.
Drag the Links control by its title bar from the
Sidebar
zone to the bottom of theMain
zone.Your page will look similar to following screen shot:
Click the Display Mode drop-down menu and select Browse.
The page is refreshed, the zone names disappear, and the Links control remains where you positioned it.
Close the browser, and then load the page again.
The changes you made are saved for future browser sessions, which demonstrates that personalization is working.
In the Display Mode menu, click Edit.
Click the arrow to display the verbs menu on the Links control, and then click the Edit verb.
The EditorZone control appears, displaying the EditorPart controls you added.
In the Appearance section of the edit control, change the Title to "My Favorites", use the Chrome Type drop-down list to select Title Only, and then click Apply.
The following screen shot shows the revised page still in edit mode:
Click the Display Mode menu, and select Browse to return to browse mode.
The control now has an updated title and no border, as shown in the following screen shot:
Adding Web Parts at Run Time
You can also enable users to add Web Parts controls to their page at run time. To do so, configure the page with a Web Parts catalog, which contains a list of Web Parts controls that you want to make available to users.
Note |
---|
In this walkthrough, you create a template containing FileUpload and Calendar controls. This will enable you to test the basic functionality of the catalog, but the resulting Web Parts controls do not have any real functionality. If you have a custom Web or user control, you can substitute it for the static content. |
To enable users to add Web Parts at run time
In the
WebPartsDemo.aspx
file, add the following:An <asp:catalogzone> element inside the third column of the table, just below the <asp:editorzone> element.
A <zonetemplate> element, and within that, an <asp:declarativecatalogpart> element and a <webpartstemplate> element.
An <asp:fileupload> element and an <asp:calendar> element.
Your code will look similar to the following code example:
<asp:catalogzone id="CatalogZone1" runat="server" headertext="Add Web Parts"> <zonetemplate> <asp:declarativecatalogpart id="catalogpart1" runat="server" Title="My Catalog"> <webPartsTemplate> <asp:fileupload runat="server" id="upload1" title="Upload Files" /> <asp:calendar runat="server" id="cal1" Title="Team Calendar" /> </webPartsTemplate> </asp:declarativecatalogpart> </zonetemplate> </asp:catalogzone>
Note The EditorZone and CatalogZone controls can both be in the same table cell because they are not displayed at the same time.
Save the
WebPartsDemo.aspx
file.
You can now test the catalog.
To test the Web Parts catalog
Load the page in a browser.
Click the Display Mode drop-down menu, and then select Catalog.
The catalog named Add Web Parts is displayed.
Drag the My Favorites control from the
Main
zone to the top of theSidebar
zone.In the Add Web Parts catalog, select both check boxes, and then select Main from the Add to drop-down list.
Click Add in the catalog.
The controls are added to the
Main
zone. If you want, you can add multiple instances of controls from the catalog to your page.The following screen shot shows the page with the file upload control and the calendar in the
Main
zone:Click the Display Mode drop-down menu, and then select Browse.
The catalog disappears and the page is refreshed.
Close the browser. Load the page again.
The changes you made persist.
Next Steps
This walkthrough has illustrated the basic principles of using simple Web Parts controls on an ASP.NET Web page. You might want to experiment with more sophisticated Web Parts features. For example, you can create Web Parts controls as user controls or custom controls. For details, see the documentation for the WebPart class.
See Also
Tasks
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Reference
Web Parts Control Set Overview
WebPart