Partilhar via


Walkthrough: Changing Display Modes on a Web Parts Page

This walkthrough illustrates two methods of changing display modes on an ASP.NET Web Parts page, and also demonstrates how a user navigates between page display modes. During this walkthrough, you will learn how to:

  • Create a custom user control that enables you to change display modes on a Web page that contains Web Parts controls.

  • Switch between the various display modes on a Web Parts page.

For more information about display modes and when to use them, see Web Parts Page Display Modes.

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 5.0 and 6.0.

  • A configured personalization provider and database. Web Parts personalization is enabled by default, and it uses the SQL personalization provider (SqlPersonalizationProvider) with the SQL Server Express (SSE) 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.

  • A custom Web Parts control derived from the WebPart class, so that you can add it to the catalog on the Web Parts page. For an example of a custom WebPart control and how to reference it in a page, see the code example for the TextDisplayWebPart control in the documentation for the WebPartDisplayMode class.

Creating a User Control to Change Display Modes

In this section you create a user control that can be added to any page containing Web Parts controls, so that users can easily switch between the various page display modes.

To create a user control to change display modes

  1. In a text editor, create a new file.

  2. At the top of the file, add a control declaration, as shown in the following code example:

    <%@ control language="vb" classname="DisplayModeMenuVB"%>
    
    <%@ control language="C#" classname="DisplayModeMenuCS"%>
    
  3. Beneath the control declaration, add the following markup to the page.

    This markup creates the user interface (UI) for the control, which consists of three main parts:

    • A drop-down list control (an <asp:dropdownlist> element) that enables users to change display modes.

    • A hyperlink (an <asp:linkbutton> element) that enables a user to reset the user-specific personalization data on the page, returning the page to its default appearance and layout prior to user modifications.

    • A pair of radio button controls (two <asp:radiobutton> elements) that enable users to switch between user and shared personalization scope (user scope is the default). When the current user personalizes the page, the personalization scope determines what range of users will be able to see the effects of the personalization.

    Your code should look like the following block of code:

    <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="&nbsp;Display Mode" 
          Font-Bold="true"
          Font-Size="8"
          Width="120" 
          AssociatedControlID="DisplayModeDropdown"/>
        <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" />
        <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>
    
    <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="&nbsp;Display Mode" 
          Font-Bold="true"
          Font-Size="8"
          Width="120" 
          AssociatedControlID="DisplayModeDropdown"/>
        <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" />
        <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>
    
  4. Name the file DisplaymodemenuCS.ascx or DisplaymodemenuVB.ascx (depending on which language you are using for the sample) and save it in the folder for the virtual directory or Web site you are using for this walkthrough.

To add display mode capabilities to the user control

  1. In the user control's source file, add a pair of <script> tags just above the opening <div> tag in the page, and add a runat="server" attribute within the opening <script> tag.

  2. Add the following code in the <script> section to enable users to change display modes on the page, to reset personalization data on the page, and to switch between user and shared personalization scope:

    <script runat="server">
      ' Use a field to reference the current WebPartManager.
      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 dropdown 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 is allowed, 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>
    
    <script runat="server">
    
     // Use a field to reference the current WebPartManager.
      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 dropdown 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 is allowed, toggle the scope.
      protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
      {
        if (_manager.Personalization.CanEnterSharedScope && 
            _manager.Personalization.Scope == PersonalizationScope.User)
          _manager.Personalization.ToggleScope();
      }
    </script>
    

    There are several things to notice in the code:

    • In the InitComplete method, the code determines which display modes are currently available on the page, and populates the drop-down list control with display modes. The code also determines whether the current user can enter into shared personalization scope on the page and selects the appropriate radio button control.

    • The DisplayModeDropdown_SelectedIndexChanged method actually changes the page's display mode, using the WebPartManager control and the mode selected by the user.

    • The LinkButton1_Click method resets the personalization state on the page, which means that all user personalization data for the page is eliminated from the personalization data store and the page is returned to its default state.

    • The RadioButton1_CheckChanged and RadioButton2_CheckChanged methods switch the personalization scope to either user or shared scope.

  3. Save and close the file.

Creating a Web Page to Host the Display Modes Control

Now that you have created a user control to change display modes, you can create a Web page that hosts the user control, and that also contains Web Parts zones and other server controls to provide Web Parts functionality.

To create a Web page that can change display modes

  1. Place the compiled assembly for the custom control your Web site's Bin folder.

    As the prerequisites for this walkthrough state, you need a compiled, custom WebPart control. This walkthrough uses the custom control called TextDisplayWebPart, which is available in the class overview topic of the WebPartDisplayMode class. The compiled assembly should be named TextDisplayWebPartCS.dll or TextDisplayWebPartVB.dll, depending on which language you use.

    Security noteSecurity Note

    The control has a text box 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.

  2. In a text editor, create a new file.

  3. At the top of the file, add a page declaration and two register directives. One register directive is for the user control; the other is for the compiled, custom WebPart control you are using for this walkthrough. The directive's Assembly attribute must reference the name of the assembly file for the custom control, without the extension.

    <%@ page language="VB" %>
    <%@ register TagPrefix="uc1" 
      TagName="DisplayModeMenuVB" 
      Src="DisplayModeMenuVB.ascx" %>
    <%@ register tagprefix="aspSample" 
      Namespace="Samples.AspNet.VB.Controls" 
      Assembly="TextDisplayWebPartVB"%>
    
    <%@ page language="C#" %>
    <%@ register TagPrefix="uc1" 
      TagName="DisplayModeMenuCS" 
      Src="DisplayModeMenuCS.ascx" %>
    <%@ register tagprefix="aspSample" 
      Namespace="Samples.AspNet.CS.Controls" 
      Assembly="TextDisplayWebPartCS"%>
    
  4. Beneath the register directives, add the following code block, which enables you to manually switch the page to catalog mode:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <script runat="server">
    Sub Button1_Click(Byval sender As Object, _
                      ByVal e As EventArgs)
      WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode
    End Sub
    </script>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <script runat="server">
    void Button1_Click(object sender, EventArgs e)
    {
      WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
    }
    </script>
    
  5. After the code block, add the following markup to the file.

    There are a number of features in this code example that are necessary to a Web Parts page, including an <asp:webpartmanager> element, Web Parts zones corresponding to the possible display modes of the page, and several controls. For more information on these, see Walkthrough: Creating a Web Parts Page.

    The code for the rest of the page should look like the following code block.

    <html xmlns="https://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
      <title>Web Parts Display Modes</title>
    </head>
    <body>
      <form id="Form2" runat="server">
        <asp:webpartmanager id="WebPartManager1" runat="server" />
        <uc1:DisplayModeMenuVB ID="DisplayModeMenu1" runat="server" />
        <asp:webpartzone
          id="WebPartZone1"
          runat="server" BackImageUrl="~/MyImage.gif">
            <zonetemplate>
              <asp:Calendar 
                ID="Calendar1" 
                Runat="server" 
                Title="My Calendar" />
            </zonetemplate>
        </asp:webpartzone>
        <asp:WebPartZone ID="WebPartZone2" Runat="server">
        </asp:WebPartZone>
        <asp:EditorZone ID="editzone1" Runat="server">
          <ZoneTemplate>
            <asp:AppearanceEditorPart 
              ID="appearanceeditor1" 
              Runat="server" />
            <asp:LayoutEditorPart 
              ID="LayoutEditorPart1" 
              Runat="server" />
          </ZoneTemplate>
        </asp:EditorZone>
        <asp:CatalogZone ID="catalogzone1" Runat="server">
          <ZoneTemplate>
            <asp:DeclarativeCatalogPart 
              ID="declarativepart1" 
              Runat="server">
              <WebPartsTemplate>
              <aspSample:TextDisplayWebPart 
                runat="server"   
                id="textwebpart" 
                title = "Text Content WebPart"/>  
              </WebPartsTemplate>
            </asp:DeclarativeCatalogPart>
          </ZoneTemplate>
        </asp:CatalogZone>
        <br />
        <asp:button
          id="button1"
          runat="server"
          text="Catalog Mode"
          OnClick="Button1_Click"
        />
      </form>
    </body>
    </html>
    
    <html xmlns="https://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
      <title>Web Parts Display Modes</title>
    </head>
    <body>
      <form id="Form2" runat="server">
        <asp:webpartmanager id="WebPartManager1" runat="server" />
        <uc1:DisplayModeMenuCS ID="DisplayModeMenu1" runat="server" />
        <asp:webpartzone
          id="WebPartZone1"
          runat="server" BackImageUrl="~/MyImage.gif">
            <zonetemplate>
              <asp:Calendar 
                ID="Calendar1" 
                Runat="server" 
                Title="My Calendar" />
            </zonetemplate>
        </asp:webpartzone>
        <asp:WebPartZone ID="WebPartZone2" Runat="server">
        </asp:WebPartZone>
        <asp:EditorZone ID="editzone1" Runat="server">
          <ZoneTemplate>
            <asp:AppearanceEditorPart 
              ID="appearanceeditor1" 
              Runat="server" />
            <asp:LayoutEditorPart 
              ID="LayoutEditorPart1" 
              Runat="server" />
          </ZoneTemplate>
        </asp:EditorZone>
        <asp:CatalogZone ID="catalogzone1" Runat="server">
          <ZoneTemplate>
            <asp:DeclarativeCatalogPart 
              ID="declarativepart1" 
              Runat="server">
              <WebPartsTemplate>
              <aspSample:TextDisplayWebPart 
                runat="server"   
                id="textwebpart" 
                title = "Text Content WebPart" AllowClose="true"/>  
              </WebPartsTemplate>
            </asp:DeclarativeCatalogPart>
          </ZoneTemplate>
        </asp:CatalogZone>
        <br />
        <asp:button
          id="button1"
          runat="server"
          text="Catalog Mode"
          OnClick="Button1_Click"
        />
      </form>
    </body>
    </html>
    
  6. Name the file Displaymodes.aspx and save it in the directory for your Web site.

Testing the Web Page to Change Display Modes

Now you have created everything necessary to run a Web page that contains Web Parts controls and that can switch between various page display modes.

To test the page and change display modes

  1. Load the page in a browser.

    The page will look similar to the following screen shot:

    Page with control for changing display modes

    Web Parts Display Modes 1

  2. Click the Display Mode drop-down list control.

    Notice the various display modes that are available on the page. Because the page contains a WebPartZone control, an EditorZone control, and a CatalogZone control, corresponding display modes appear in the drop-down list for each of these zone types, in addition to the default Browse display mode.

    Note

    The page could also contain a ConnectionsZone control, which would enable you to create connections between controls and would add a connection display mode to the drop-down list. However, connections are beyond the scope of this walkthrough.

  3. Select Catalog mode from the drop-down list.

    The catalog mode UI appears, and the TextDisplayWebPart control is visible in the catalog, available to be added to the page.

  4. Click the Close button to return the page to browse mode.

  5. As an alternate way of switching to a display mode, without requiring the user control, click the Catalog Mode button near the bottom of the page. The code for this switch appears in the Web page's Button1_Click method.

    The page switches to catalog mode.

  6. Select the check box next to the custom control in the catalog, and click Add to add it to the page.

  7. Click Close to return the page to browse mode.

    The added control now appears on the page.

  8. In the Display Mode drop-down list control, select Edit.

    The page switches to edit mode. The titles of the zones become visible, and a verbs menu button that looks like a small triangle appears in the title bar of each server control residing in a WebPartZone. The verbs menu provides various actions that a user can apply to a control.

  9. Click the verbs menu on the TextDisplayWebPart control.

    A drop-down menu appears.

  10. In the verbs menu, click the Edit option.

    The special editing UI, which is declared in the <asp:editorzone> element, appears. With these controls, you can change the layout and appearance of the custom control.

  11. Use the editing UI to change the title of the custom control. Then click Apply to apply the changes.

  12. Position your mouse pointer in the title bar of the custom control. Click the title bar and drag the control from WebPartZone1 into WebPartZone2.

  13. Use the Display Mode drop-down list control to change the page back to browse mode.

    The page will look similar to the following screen shot.

    Page after making changes in various display modes

    WebParts DisplayMode 2

See Also

Tasks

Walkthrough: Creating a Web Parts Page

Reference

Web Parts Control Set Overview

WebPartDisplayMode

Concepts

Web Parts Page Display Modes