演练:更改 Web 部件页上的显示模式

更新:2007 年 11 月

本演练阐释两种更改 ASP.NET Web 部件页上的显示模式的方法,并演示用户如何在页面显示模式之间导航。通过本演练,您将学会如何执行以下任务:

  • 创建一个自定义用户控件,用于更改包含 Web 部件控件的网页上的显示模式。

  • 在 Web 部件页上的各种显示模式之间切换。

有关显示模式及其使用时机的更多信息,请参见 Web 部件页显示模式

先决条件

若要完成本演练,您需要:

  • 已在将承载该站点的计算机上安装和配置的 Internet 信息服务 (IIS)。有关安装和配置 IIS 的详细信息,请参见安装中附带的 IIS 帮助文档,或者参见 Microsoft TechNet 网站(“Internet Information Services 6.0 Technical Resources”(Internet 信息服务 6.0 技术资源))上的联机 IIS 文档。

  • 可识别单个用户的 ASP.NET 网站。如果已经配置了这样的站点,则可以将该站点用作本演练的起始点。否则,请参见如何:在 IIS 5.0 和 6.0 中创建和配置虚拟目录获取有关创建虚拟目录或站点的详细信息。

  • 已配置的个性化设置提供程序和数据库。默认情况下启用 Web 部件个性化设置,而且它使用 SQL 个性化设置提供程序 (SqlPersonalizationProvider) 和 SQL Server Express (SSE) 版本来存储个性化设置数据。本演练使用 SSE 和默认的 SQL 提供程序。如果安装了 SSE,则不需要进行任何配置。SSE 是作为 Microsoft Visual Studio 2005 安装的可选部分提供的,也可以免费下载。有关详细信息,请参见 Microsoft SQL Server 2005 Express Edition 网页。若要使用 SQL Server 的一个完整版本,必须安装和配置 ASP.NET 应用程序服务数据库,并且将 SQL 个性化设置提供程序配置为连接到该数据库。有关详细信息,请参见为 SQL Server 创建和配置应用程序服务数据库。还可以创建和配置自定义提供程序来使用其他非 SQL 数据库或存储解决方案。有关详细信息和代码示例,请参见实现成员资格提供程序

  • 一个自定义 Web 部件控件从 WebPart 类派生,以便您可以将它添加到 Web 部件页上的目录中。有关自定义 WebPart 控件的示例以及如何在页面中引用它,请参见 WebPartDisplayMode 类所对应的文档中的 TextDisplayWebPart 控件的代码示例。

创建用户控件以更改显示模式

在本节中,将创建一个可以添加到包含 Web 部件控件的任何页面的用户控件,以便用户可以轻松地在各种页面显示模式之间切换。

创建用户控件以更改显示模式

  1. 在文本编辑器中,创建一个新文件。

  2. 在该文件的顶端添加一个控件声明,如下面的代码示例所示:

    <%@ control language="vb" classname="DisplayModeMenuVB"%>
    
    <%@ control language="C#" classname="DisplayModeMenuCS"%>
    
  3. 在控件声明下面,向页面添加以下标记。

    此标记将创建该控件的用户界面 (UI),用户界面由三个主要部分组成:

    • 一个下拉列表控件(一个 <asp:dropdownlist> 元素),它使用户能够更改显示模式。

    • 一个超链接(一个 <asp:linkbutton> 元素),它使用户能够重置页面上用户特定的个性化设置数据,以将页面返回到用户修改前的默认外观和布局。

    • 一对单选按钮控件(两个 <asp:radiobutton> 元素),它们使用户能够在用户个性化设置范围和共享个性化设置范围之间切换(用户范围是默认设置)。在当前用户个性化页面时,个性化设置范围确定哪个范围的用户将能够看到个性化设置的效果。

    您的代码应类似于以下代码块:

    <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. 将文件命名为 DisplaymodemenuCS.ascx 或 DisplaymodemenuVB.ascx(具体取决于此示例使用哪种语言),并保存在本演练所使用的虚拟目录或网站对应的文件夹内。

将显示模式功能添加到用户控件

  1. 在用户控件的源文件中,在页面的 <div> 开始标记紧前面添加一对 <script> 标记,并在 <script> 开始标记内添加一个 runat="server" 属性。

  2. 在 <script> 节中添加下面的代码,以使用户能够更改页面上的显示模式、重置页面上的个性化设置数据以及在用户个性化设置范围与共享个性化设置范围之间切换:

    <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>
    

    在此代码中,请注意以下几点:

    • 在 InitComplete 方法中,代码确定页面当前可以使用哪些显示模式,并使用显示模式填充下拉列表控件。代码还确定当前用户是否可以进入页面上的共享个性化设置范围,并选择适当的单选按钮控件。

    • DisplayModeDropdown_SelectedIndexChanged 方法实际上使用 WebPartManager 控件和用户选择的模式更改页面的显示模式。

    • LinkButton1_Click 方法重置页面上的个性化设置状态,这意味着页面的所有用户个性化设置数据将从个性化设置数据存储区中清除,而页面将返回其默认状态。

    • RadioButton1_CheckChanged 和 RadioButton2_CheckChanged 方法将个性化设置范围切换为用户范围或共享范围。

  3. 保存并关闭文件。

创建用于承载显示模式控件的网页

由于您已创建了一个更改显示模式的用户控件,因此可以创建一个网页来承载该用户控件,该网页还包含 Web 部件区域和其他服务器控件以提供 Web 部件功能
。

创建可以更改显示模式的网页

  1. 将自定义控件的已编译程序集置于网站的 Bin 文件夹中。

    作为本演练状态的必备条件,需要一个编译好的自定义 WebPart 控件。本演练使用称为 TextDisplayWebPart 的自定义控件,可以在 WebPartDisplayMode 类的类概述主题中找到该控件。编译后的程序集应命名为 TextDisplayWebPartCS.dll 或 TextDisplayWebPartVB.dll,具体取决于您使用的语言。

    bw5tctbb.alert_security(zh-cn,VS.90).gif安全说明:

    该控件具有一个接受用户输入的文本框,这将是一个潜在的安全威胁。默认情况下,ASP.NET 网页验证用户输入,以确保输入中不包含 HTML 元素或脚本。有关更多信息,请参见脚本侵入概述

  2. 在文本编辑器中,创建一个新文件。

  3. 在该文件的顶端,添加一个页面声明和两个 register 指令。一个 register 指令用于用户控件;另一个指令用于供本演练使用的编译后的自定义 WebPart 控件。指令的 Assembly 属性必须引用自定义控件的程序集文件名(不包括扩展名)。

    <%@ 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. 在 register 指令的下面,添加以下允许您手动将页面切换到目录模式的代码块:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://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"
        "http://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. 在这段代码块之后,添加该文件的以下标记。

    此代码示例中有一个 Web 部件页所必需的许多功能,而该页包含一个 <asp:webpartmanager> 元素、对应于页面的可能的显示模式的 Web 部件区域以及几个控件。有关这些内容的更多信息,请参见演练:创建 Web 部件页

    用于页面其余部分的代码看起来应该类似于以下代码块。

    <html xmlns="http://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="http://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. 将该文件命名为 Displaymodes.aspx,并保存在您的网站的目录中。

测试要更改显示模式的网页

现在您已经创建了运行下面这样的一个网页所必需的所有内容:该网页包含 Web 部件控件并且可以在各种页面显示模式之间切换。

测试页面和更改显示模式

  1. 在浏览器中加载页。

    页面看起来将类似于下面的屏幕快照:

    具有用于更改显示模式的控件的页面
    Web 部件显示模式 1

  2. 单击**“显示模式”**下拉列表控件。

    请注意可用于页面的各种显示模式。由于页面包含一个 WebPartZone 控件、一个 EditorZone 控件和一个 CatalogZone 控件,因此这些区域类型的每种类型对应的显示模式将出现在下拉列表中,另外还显示默认的**“浏览”**显示模式。

    bw5tctbb.alert_note(zh-cn,VS.90).gif说明:

    页面还可包含 ConnectionsZone 控件,此控件允许您在控件之间建立连接,并会向该下拉列表中添加一个连接显示模式。但是,这些连接已超出本演练的范围。

  3. 从下拉列表中选择**“目录”**模式。

    将出现目录模式 UI,在目录中可以看到 TextDisplayWebPart 控件并可以将此控件添加到页面中。

  4. 单击**“关闭”**按钮将页面返回到浏览模式。

  5. 作为切换显示模式的一种替代方式,不必使用用户控件,只需单击页面底端附近的**“目录模式”**按钮。用于此切换的代码显示在网页的 Button1_Click 方法中。

    页面将切换到目录模式。

  6. 在目录中选择该自定义控件旁边的复选框,再单击**“添加”**以将其添加到页面上。

  7. 单击**“关闭”**按钮将页面返回到浏览模式。

    添加的控件立刻会出现在页面上。

  8. 在**“显示模式”下拉列表控件中,选择“编辑”**。

    页面将切换到编辑模式。区域的标题将变得可见,并且有一个看起来类似小三角形的谓词菜单按钮显示在 WebPartZone 中的每个服务器控件的标题栏内。该谓词菜单提供用户可应用于控件的各个操作。

  9. 单击 TextDisplayWebPart 控件上的谓词菜单。

    将显示一个下拉菜单。

  10. 在谓词菜单中,单击**“编辑”**选项。

    将显示特殊的编辑 UI,它是在 <asp:editorzone> 元素内声明的。使用这些控件可以更改自定义控件的布局和外观。

  11. 使用编辑 UI 更改自定义控件的标题。然后单击**“应用”**以应用更改。

  12. 将鼠标指针放在自定义控件的标题栏中。单击该标题栏,然后将控件从 WebPartZone1 拖动到 WebPartZone2 中。

  13. 使用**“显示模式”**下拉列表控件将页面更改回浏览模式。

    页面看起来将类似于下面的屏幕快照。

    在各种显示模式下进行更改后的页面
    Web 部件显示模式 2

请参见

任务

演练:创建 Web 部件页

概念

Web 部件页显示模式

参考

Web 部件控件集概述

WebPartDisplayMode