WebPartManager.DisconnectWebPart(WebPart) Método

Definición

Quita un control WebPart o control de servidor que se cierra o elimina de cualquier conexión en la que esté participando.

protected:
 virtual void DisconnectWebPart(System::Web::UI::WebControls::WebParts::WebPart ^ webPart);
protected virtual void DisconnectWebPart (System.Web.UI.WebControls.WebParts.WebPart webPart);
abstract member DisconnectWebPart : System.Web.UI.WebControls.WebParts.WebPart -> unit
override this.DisconnectWebPart : System.Web.UI.WebControls.WebParts.WebPart -> unit
Protected Overridable Sub DisconnectWebPart (webPart As WebPart)

Parámetros

webPart
WebPart

Control WebPart que se va a desconectar.

Ejemplos

En el ejemplo de código siguiente se muestra cómo utilizar el método DisconnectWebPart. Con dos controles personalizados WebPart , la página web permite crear una conexión entre los controles haciendo clic en un botón, mientras que otro botón le permite desconectar los controles. Si cierra uno de los controles mientras la página está en modo de exploración y los controles están conectados, una invalidación del método desconecta el DisconnectWebPart control cerrado, finaliza la conexión y muestra un mensaje.

El ejemplo de código tiene cuatro partes:

  • Control de usuario para cambiar los modos de presentación.

  • Un archivo de origen que contiene controles personalizados WebPart .

  • Una página web para hospedar los controles.

  • Explicación de cómo funciona el ejemplo en un explorador.

La primera parte del ejemplo de código es el control de usuario para cambiar los modos de presentación. Puede obtener el código fuente del control de usuario en la sección Ejemplo de la información general de la WebPartManager clase. Para obtener más información sobre los modos de presentación y cómo funciona el control de usuario, vea Walkthrough: Changing Display Modes on a Web Parts Page.

La segunda parte es el archivo que contiene el código fuente de los dos controles personalizados WebPart que se conectarán y un control personalizado WebPartManager . Para que se ejecute el ejemplo de código, debe compilar este código fuente. Puede compilarlo explícitamente y colocar el ensamblado resultante en la carpeta Bin del sitio web o en la caché global de ensamblados. Como alternativa, puede colocar el código fuente en la carpeta App_Code del sitio, donde se compilará dinámicamente en tiempo de ejecución. En este ejemplo se usa la compilación dinámica, por lo que la Register directiva que hace referencia a estos componentes en la página web se declara en consecuencia en la parte superior de la página web. Para ver un tutorial que muestra las opciones de compilación, vea Walkthrough: Developing and Using a Custom Web Server Control.

En el código fuente, observe el control MyWebPartManager heredado que invalida el DisconnectWebPart método . Este método comprueba cada conexión de una página para ver si el control que se va a cerrar participa en la conexión y, si es así, llama al DisconnectWebParts método para finalizar la conexión. Esto es idéntico a la implementación base del método en el WebPartManager control . A continuación, el método invalidado personaliza la implementación base escribiendo un mensaje en la página.

namespace Samples.AspNet.CS.Controls
{
  using System;
  using System.Web;
  using System.Web.Security;
  using System.Security.Permissions;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public interface IZipCode
  {
    string ZipCode { get; set;}
  }

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class ZipCodeWebPart : WebPart, IZipCode
  {
    string zipCodeText = String.Empty;
    TextBox input;
    Button send;

    public ZipCodeWebPart()
    {
    }

    // Make the implemented property personalizable to save 
    // the Zip Code between browser sessions.
    [Personalizable()]
    public virtual string ZipCode
    {
      get { return zipCodeText; }
      set { zipCodeText = value; }
    }

    // This is the callback method that returns the provider.
    [ConnectionProvider("Zip Code", "ZipCodeProvider")]
    public IZipCode ProvideIZipCode()
    {
      return this;
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();
      input = new TextBox();
      this.Controls.Add(input);
      send = new Button();
      send.Text = "Enter 5-digit Zip Code";
      send.Click += new EventHandler(this.submit_Click);
      this.Controls.Add(send);
    }

    private void submit_Click(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(input.Text))
      {
        zipCodeText = Page.Server.HtmlEncode(input.Text);
        input.Text = String.Empty;
      }
    }
  }

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class WeatherWebPart : WebPart
  {
    private IZipCode _provider;
    string _zipSearch;
    Label DisplayContent;

    // This method is identified by the ConnectionConsumer 
    // attribute, and is the mechanism for connecting with 
    // the provider. 
    [ConnectionConsumer("Zip Code", "ZipCodeConsumer")]
    public void GetIZipCode(IZipCode Provider)
    {
      _provider = Provider;
    }
    
    protected override void OnPreRender(EventArgs e)
    {
      EnsureChildControls();

      if (this._provider != null)
      {
        _zipSearch = _provider.ZipCode.Trim();
        DisplayContent.Text = "My Zip Code is:  " + _zipSearch;
      }
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();
      DisplayContent = new Label();
      this.Controls.Add(DisplayContent);
    }
  }
}
Imports System.Web
Imports System.Web.Security
Imports System.Security.Permissions
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Interface IZipCode

    Property ZipCode() As String

  End Interface

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class ZipCodeWebPart
    Inherits WebPart
    Implements IZipCode
    Private zipCodeText As String = String.Empty
    Private input As TextBox
    Private send As Button

    Public Sub New()
    End Sub

    ' Make the implemented property personalizable to save 
    ' the Zip Code between browser sessions.
    <Personalizable()> _
    Public Property ZipCode() As String _
      Implements IZipCode.ZipCode

      Get
        Return zipCodeText
      End Get
      Set(ByVal value As String)
        zipCodeText = value
      End Set
    End Property

    ' This is the callback method that returns the provider.
    <ConnectionProvider("Zip Code", "ZipCodeProvider")> _
    Public Function ProvideIZipCode() As IZipCode
      Return Me
    End Function


    Protected Overrides Sub CreateChildControls()
      Controls.Clear()
      input = New TextBox()
      Me.Controls.Add(input)
      send = New Button()
      send.Text = "Enter 5-digit Zip Code"
      AddHandler send.Click, AddressOf Me.submit_Click
      Me.Controls.Add(send)

    End Sub


    Private Sub submit_Click(ByVal sender As Object, _
      ByVal e As EventArgs)

      If input.Text <> String.Empty Then
        zipCodeText = Page.Server.HtmlEncode(input.Text)
        input.Text = String.Empty
      End If

    End Sub

  End Class

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class WeatherWebPart
    Inherits WebPart
    Private _provider As IZipCode
    Private _zipSearch As String
    Private DisplayContent As Label

    ' This method is identified by the ConnectionConsumer 
    ' attribute, and is the mechanism for connecting with 
    ' the provider. 
    <ConnectionConsumer("Zip Code", "ZipCodeConsumer")> _
    Public Sub GetIZipCode(ByVal Provider As IZipCode)
      _provider = Provider
    End Sub


    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
      EnsureChildControls()

      If Not (Me._provider Is Nothing) Then
        _zipSearch = _provider.ZipCode.Trim()
                DisplayContent.Text = "My Zip Code is:  " + _zipSearch
      End If

    End Sub

    Protected Overrides Sub CreateChildControls()
      Controls.Clear()
      DisplayContent = New Label()
      Me.Controls.Add(DisplayContent)

    End Sub

  End Class

End Namespace

La tercera parte del ejemplo de código es la página web. Observe que, cerca de la parte superior, contiene Register directivas para registrar el control de usuario y el ensamblado compilado dinámicamente con los WebPart controles. La página tiene dos métodos principales. El Button1_Click método crea una conexión entre los controles, mientras que el Button2_Click método desconecta los controles.

<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc1" 
    TagName="DisplayModeMenuCS"
    Src="~/displaymodemenucs.ascx" %>
<%@ Register TagPrefix="aspSample" 
    Namespace="Samples.AspNet.CS.Controls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    
  protected void Button1_Click(object sender, EventArgs e)
  {
    ProviderConnectionPoint provPoint =
      mgr.GetProviderConnectionPoints(zip1)["ZipCodeProvider"];
    ConsumerConnectionPoint connPoint =
      mgr.GetConsumerConnectionPoints(weather1)["ZipCodeConsumer"];
    WebPartConnection conn1 = mgr.ConnectWebParts(zip1, provPoint,
      weather1, connPoint);
  }

  protected void Button2_Click(object sender, EventArgs e)
  {
    if (mgr.Connections.Count >= 1 && mgr.Connections[0] != null)
      mgr.DisconnectWebParts(mgr.Connections[0]);
  }
  

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="mgr" runat="server">
      </asp:WebPartManager>
      <uc1:DisplayModeMenuCS ID="menu1" runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <aspSample:ZipCodeWebPart ID="zip1" runat="server"
            Title="Zip Code Provider" />
          <aspSample:WeatherWebPart ID="weather1" runat="server" 
            Title="Zip Code Consumer" />
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
      </asp:ConnectionsZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Connect WebPart Controls" 
        OnClick="Button1_Click" />
      <asp:Button ID="Button2" runat="server" 
        Text="Disconnect WebPart Controls" 
        OnClick="Button2_Click" />
    </div>
    </form>
</body>
</html>
<%@ Page Language="vb" %>
<%@ Register TagPrefix="uc1" 
    TagName="DisplayModeMenuVB"
    Src="~/displaymodemenuvb.ascx" %>
<%@ Register TagPrefix="aspSample" 
    Namespace="Samples.AspNet.VB.Controls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Protected Sub Button1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    
    Dim mgr As WebPartManager = _
      WebPartManager.GetCurrentWebPartManager(Page)
    Dim provPoint As ProviderConnectionPoint = _
      mgr.GetProviderConnectionPoints(zip1)("ZipCodeProvider")
    Dim connPoint As ConsumerConnectionPoint = _
      mgr.GetConsumerConnectionPoints(weather1)("ZipCodeConsumer")
    mgr.ConnectWebParts(zip1, provPoint, weather1, connPoint)

  End Sub
  
  Protected Sub Button2_Click(ByVal sender as Object, _
    ByVal e as System.EventArgs)
    
    If mgr.Connections.Count >= 1 AndAlso _
      mgr.Connections(0) IsNot Nothing Then
      mgr.DisconnectWebParts(mgr.Connections(0))
    End If
    
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="mgr" runat="server">
      </asp:WebPartManager>
      <uc1:DisplayModeMenuVB ID="menu1" runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <aspSample:ZipCodeWebPart ID="zip1" runat="server"
            Title="Zip Code Provider" />
          <aspSample:WeatherWebPart ID="weather1" runat="server" 
            Title="Zip Code Consumer" />
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
      </asp:ConnectionsZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Connect WebPart Controls" 
        OnClick="Button1_Click" />
      <asp:Button ID="Button2" runat="server" 
        Text="Disconnect WebPart Controls" 
        OnClick="Button2_Click" />
    </div>
    </form>
</body>
</html>

Después de cargar la página, haga clic en el botón Conectar para conectar los controles. A continuación, haga clic en el menú verbos de uno de los controles (la flecha hacia abajo del encabezado del control) y seleccione Cerrar en el menú verbos. Al intentar cerrar el control, se llama al método invalidado, se finaliza la conexión y se escribe el mensaje en la página. Si desea restablecer la página para restaurar el control cerrado y experimentar con otras opciones, haga clic en el vínculo Restablecer estado de usuario para quitar los datos de personalización y restaurar el estado original de la página.

Comentarios

El DisconnectWebPart control de elementos web llama internamente al método establecido cuando un control se cierra en una página o se elimina de una página. En este escenario, se llama al método para quitar el control de las conexiones en las que está implicado como consumidor o proveedor. Si el control se quita de cualquier conexión, este método también llama al DisconnectWebParts método para finalizar cualquier conexión en la que webPart se haya implicado.

Cuando se llama al DisconnectWebPart método , genera el WebPartsDisconnecting evento . Normalmente, este evento se puede cancelar, pero en dos casos no se puede cancelar. Un caso se produce durante las solicitudes a la página, cuando se llama al ActivateConnections método . Si hay un conflicto entre las conexiones existentes, se invocará el DisconnectWebPart método para cerrar una de las conexiones en conflicto y, en este caso, el WebPartsDisconnecting evento no se puede cancelar, porque el conflicto debe resolverse.

El otro caso se produce cuando se cierra o elimina un WebPart control de servidor o que está conectado actualmente. En este caso, debido a que el control se quita de la página, su conexión también debe finalizarse, por lo tanto, por diseño no es posible cancelar el WebPartsDisconnecting evento para interrumpir el proceso de finalización de una conexión. Para obtener más información, vea el evento WebPartsDisconnecting.

Se aplica a

Consulte también