ASP.NET WebParts Connections Tutorial

该博客主要介绍了ASP.NET中使用WebPart连接的方法。包括定义连接接口、创建提供者WebPart和消费者WebPart、建立连接等步骤,还给出了创建新项目、页面及运行示例的详细操作,帮助开发者掌握WebPart连接的实现。

Introduction


Connections are a very powerful feature of WebParts that allows interchanging data between two webparts, allowing creating more interesting non-monolitic WebParts.

Creating a connection is as easy as defining the interface that you want to connect through. Think of it as the contract you are saying your WebPart supports and that someone could at runtime request that interface and use it.

To have a connection one WebPart should act as a Provider and another WebPart should act as a Consumer. The Provider exposes some data through a well defined interface, that the consumer knows how to use.

Lets start creating the simplest Connection Sample possible, and as with all samples we will start with the “Hello World” connection sample.

Using WebPart Connections

The steps we need to follow to establish a connection are:
  • Define the interface that will connect both webparts
  • Create a Provider WebPart
    • a. Expose a Provider connection point to return this interface in a WebPart
  • Create a Consumer WebPart
    • a. Expose a Consumer connection point to request the interface
  • Establish the connection
  • Use the Interface in PreRender

Sample Scenario


The scenario that we will create is as simple as it gets. We will create a Provider WebPart that will expose a single string property (called Message) that will be consumed by another WebPart through a Connection. The consumer WebPart will only display the Message in a Label.

To make it interactive we will expose a TextBox that will allow to change the Message property in the Provider and this will update the Consumer as well.

Create a new Project


Create a new Web Application in Visual Web Developer or Visual Studio .NET.

Define the Interface for the connection

The first step is to define the interface through which the WebParts will communicate. The ASP.NET WebPart Framework ships several interfaces to try to standardize a little bit the creation of new webparts to try to enhance the intercommunication between vendors, for example IField, IParameter, IRow, ITable, etc. You can also define your own interface if you want to.
In this sample since all the data we need to interchange is a string property we will define our own interface.

Create the Code Directory
  • Select the project node in the Solution Explorer.
  • Right click it and select New Folder
  • Type Code as the name of the folder
Note. the Code directory is new to ASP.NET 2.0 that allows developers to place code inside this directory with the .cs or .vb extension and the asp.net build infrastructure will compile the code on demand only when needed.

Add a new Interface in the Code directory.
  • Select the Code folder
  • Right click it and select the option Add New Item
  • Select the option Class and type as the name IMessage
  • Replace the content of the generated class with the following code.
C# Code:

public interface IMessage {
    string Message { get;}
}

VB.NET Code:

Public Interface IMessage
    ReadOnly Property Message() As String
End Interface

Create the Provider WebPart

After defining the interface, we need to create the WebPart that will expose it as a Provider.
To simplify the sample we will create a UserControl that we will use as a webpart, this is a really easy way to build webpart without having to understand the whole WebPart infrastructure.
Side Note: The WebPart framework only knows how to process WebParts, if you add a control that does not inherit from WebPart directly or indirectly (say UserControls, WebControls, etc) then the WebParts Framework will "wrap" the control in a especial type of WebPart called GenericWebPart, this GenericWebPart class will try to look for specific WebPart attributes (ie those defined in IWebPart interface like Title, SubTitle, Description, etc) and extract the values to make it behave just as any other WebPart.

Create the User Control
  • Select the Project node
  • Right click it and select the option Add New Item
  • Select the option Web User Control
  • Type ProviderWebPart.ascx as the name for the UserControl
  • Replace the content of the UserControl so that it looks as the following code 
C# Code

<%@ Control Language="C#" ClassName="ProviderWebPart" %>
<%@ Implements Interface="IMessage" %>
<script runat="server">
    
    [ConnectionProvider("Message")]
    
public IMessage GetMessage() {
        return this;
    }
    
    public string Message {
        get {
            return _messageTextBox.Text;
        }
    }
</script>
<asp:TextBox Runat="server" ID="_messageTextBox" />
<asp:Button Runat="server" ID="_postBackButton" Text="Change the Text" />
VB.NET Code

<%@ Control Language="VB" ClassName="ProviderWebPart" %>
<%@ Implements Interface="IMessage" %>
<script runat='server'>
    
    
Public ReadOnly Property Message() As String _
        Implements IMessage.Message
        Get
            Return _messageTextBox.Text
        End Get
    End Property
    
    <ConnectionProvider("Message")> _
    Public Function GetMessage() As IMessage
        Return Me
    End Function
</script>
<asp:TextBox Runat="server" ID="_messageTextBox" />
<asp:Button Runat="server" ID="_postBackButton" Text="Change the Text" />
This code defines a control that implements the interface IMessage that was previously defined.
It exposes a method called GetMessage() that returns an instance of such interface, since in this case the control itself implements the interface, it is safe to return this. You could potentially create an instance of another object and returned it if needed.

This method has a Custom attribute that signals the ASP.NET WebPart framework that this method is to expose a Provider Connection Point so other webparts can connect to it.

Then it actually implements the Message property of the IMessage interface to return the value of the TextBox (_messageTextBox).

Finally I just added a button so we can change the text and click the button to see the Connections working.

Create the Consumer WebPart

Now we will create the consumer of such WebPart.
To simplify the sample we will create it using again a UserControl.

Create the User Control
  • Select the Project node
  • Right click it and select the option Add New Item
  • Select the option Web User Control
  • Type ConsumerWebPart.ascx as the name for the UserControl
  • Replace the content of the UserControl so that it looks as the following code 
C# Code

<%@ Control Language="C#" ClassName="ConsumerWebPart" %>

<script runat="server">
    
private IMessage _message;
    
    [ConnectionConsumer("Message")]
    void SetMessage(IMessage message) {
        this._message = message;
    }

    protected override void OnPreRender(EventArgs e) {
        if (_message != null
            _messageLabel.Text = _message.Message;
        base.OnPreRender(e);
    }

</script>
<asp:Label Runat="server" ID="_messageLabel" />
VB.NET Code

<%@ Control Language="VB" ClassName="ConsumerWebPart" %>

<script runat='server'>
    
    
Private _message As IMessage
    
    <ConnectionConsumer("Message")>  _
    Sub SetMessage(ByVal message As IMessage)
        Me._message = message
    End Sub
    
    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
        If (Not (_message) Is NothingThen
            _messageLabel.Text = _message.Message
        End If
        MyBase.OnPreRender(e)
    End Sub
</script>
<asp:Label Runat="server" ID="_messageLabel" />
This code defines a WebPart that acts as a consumer of the previous WebPart.
The way it works is it exposes a method that is marked with the attribute ConnectionConsumer. This attribute signals ASP.NET WebPart Connections Framework that this method acts as a "receiver" of the IMessage interface.
At runtime the WebPart framework will request the Interface from the Provider and then it will call the SetMessage method passing the instance as the argument.

Note:One important thing to notice here is that you should not use the interface at this moment, it is only safe to use in the PreRender due to the fact that connections might depend on other connections and you can only be sure everything is set up correctly at the PreRender.
For this reason the only thing we do here is save a reference to such interface, so that we can use it in the PreRender to actually extract the values.

Creating the page

Now we will create the page where we actually use both webparts.

Create the Page
  • Select the Project node
  • Right click it and select the option Add New Item
  • Select the option Web Form
  • Type Sample.aspx as the name for the Page
  • Replace the content of the Page so that it looks as the following code 

C# Code

<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc1" TagName="ProviderWebPart" Src="ProviderWebPart.ascx" %>
<%@ Register TagPrefix="uc2" TagName="ConsumerWebPart" Src="ConsumerWebPart.ascx" %>
<html>
<head>
    
<title>Sample Page</title>
</head>
<body>
    
<form id="form1" runat="server">
        
<asp:WebPartManager ID="WebPartManager1" Runat="server">
            
<StaticConnections>
                
<asp:Connection ID="SampleConnection" ConsumerID="ConsumerWebPart1" ProviderID="ProviderWebPart1" />
            
</StaticConnections>
        
</asp:WebPartManager>
        
<asp:WebPartZone ID="WebPartZone1" Runat="server">
            
<ZoneTemplate>
                
<uc1:ProviderWebPart Runat="server" ID="ProviderWebPart1" />
                
<uc2:ConsumerWebPart Runat="server" ID="ConsumerWebPart1" />
            
</ZoneTemplate>
        
</asp:WebPartZone>
    
</form>
</body>
</html>
VB.NET Code

<%@ Page Language="VB" %>
<%@ Register TagPrefix="uc1" TagName="ProviderWebPart" Src="ProviderWebPart.ascx" %>
<%@ Register TagPrefix="uc2" TagName="ConsumerWebPart" Src="ConsumerWebPart.ascx" %>
<html>
<head>
    
<title>Sample Page</title>
</head>
<body>
    
<form id="form1" runat="server">
        
<asp:WebPartManager ID="WebPartManager1" Runat="server">
            
<StaticConnections>
                
<asp:Connection ID="SampleConnection" ConsumerID="ConsumerWebPart1" ProviderID="ProviderWebPart1" />
            
</StaticConnections>
        
</asp:WebPartManager>
        
<asp:WebPartZone ID="WebPartZone1" Runat="server">
            
<ZoneTemplate>
                
<uc1:ProviderWebPart Runat="server" ID="ProviderWebPart1" />
                
<uc2:ConsumerWebPart Runat="server" ID="ConsumerWebPart1" />
            
</ZoneTemplate>
        
</asp:WebPartZone>
    
</form>
</body>
</html>

Running the Sample


To run the sample just browse to Sample.aspx.
Type some text in the TextBox and then click the Button.
Notice how the Consumer WebPart will automatically display the data from the Provider WebPart.

Summary


Connections are a very powerfull feature in WebParts that allow WebParts to interact data between them without having to know the details of the implementation.
In this tutorial we just scratched the surface of Connections, they are as complicated and rich as the whole WebPart Framework, they support several features, including multiple connections, Transformers (to adapt incompatible connections), one to many connections, secondary interfaces and many many more.
代码下载链接: https://pan.quark.cn/s/a175d1ef418b 标题部分中的"新建文件夹 (2).zip"暗示这是一个采用ZIP编码方式的压缩文档,这种格式通常用于将多个关联的文件或目录整合进一个压缩单元中。在信息技术领域,ZIP编码格式是一种广泛应用的标准,它支持将多个数据单元压缩成一个独立的压缩文件,从而提升文件传输的便捷性、存储空间的利用效率以及管理的便捷度。ZIP格式的压缩文件可以通过多种解压缩工具进行访问,例如WinRAR软件、7-Zip应用程序或操作系统自带的压缩解压功能。 描述文本里的"shop"字样或许指向这个压缩文档与商业店铺、电子商务平台或网络销售系统存在关联。在Java编程范畴内,这有可能是一个范例项目,用以说明构建电子商务平台相关功能的实现方法,涵盖商品维护、购物车功能以及订单处理等模块。Java语言因其跨平台兼容性、系统稳定性以及完备的库资源支持,经常被选作开发大型企业级应用的技术栈,尤其是电子商务系统。 依据标签"java"的指示,可以推断压缩包内部可能包含了采用Java编程语言编写的源代码片段、系统配置文档、数据库操作脚本及其他辅助性资源。Java程序员一般借助集成开发环境(IDE)如Eclipse、IntelliJ IDEA或NetBeans进行Java代码的编写、编译及执行操作。这些开发工具能够高效地支持ZIP文件中项目结构的导入与管理。 文件命名列表仅列出一个条目"新建文件夹 (2)",这或许意味着压缩文档中包含一个同名的文件夹,该文件夹内可能收纳了一系列子文件及子目录。在实际的Java开发任务中,类似的结构可能包含src目录(存放程序源代码)、lib目录(存放项目依赖的jar库文件)、resou...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值