WebPart之间如何通信

1.新建一个Web窗体命名为WebPartDemo.aspx

2.创建一个用户控件Event.ascx,其中包含一个DropDownList控件,为其填充几组值。创建一个用户控件Country.ascs,其中只包含一个Lable控件

3.在WebPartDemo.aspx的顶部添加一个WebPartManager控件,再添加一个一行两列的表格,放两个WebParZonet控件进去。两个WebPartZone控件里分别
放入Event.用户控件和Country用户控件。

现在要在第二个WebPart的Country控件中显示第一个WebPart里的DropDownList的值。由于各个区域的用户控件不能相互访问, 用普通的事件处理程序无法办到。

WebPartManager负责初始化和管理 Web Parts之间的通信。Web Parts之间的通信需要区分消费者和提供者。提供者提供一些数据,消费者使用该数据。首先,WebPartManager从提供者处调用方法,获得可以访问的接口,以接收数据。提供者用[ConnectionProvider]属性来标识。接着,WebPartManager把这些接口传送给

消费者。消费者用[ConnectionConsumer]属性标识。现在,消费者就可以调用提供者的方法接收数据了。

具体实现如下:

创建一个新的c#文件ICountry.cs,定义ICountry接口;

public interface ICountry
{
string GetCountry;

}

打开之前创建的用户控件Event的源代码,用Event类实现ICountry接口,执行GetCountry()方法,向调用者显示选中的值。

public partial class Events : System.Web.UI.UserControl, ICountry
{
    public string GetCountry()
    {
        return dropCountries.SelectedItem.Value;
    }
// ...
提供者也需要一个用[ConnectionProvider]属性标记的方法,该方法必须返回一个接口。执行GetCountryInterface()方法,返回对ICounry接口的引用。属性[ConnectionProvider]给提供者定义了一个友好的名称(Event)和一个实际名称(CountryProvider),在Event..ascx.cs中添加下面的代码:

 [ConnectionProvider("Event1", "CountryProvider")]
    public ICountry GetCountryInterface()
    {
        return this;
    }
打开用户控件的c#代码,执行用 [ConnectionConsumer]属性标记的消费者方法。方法SetCountry()接收ICountry接口,用于调用GetCountry()方法,接收来自提供者的数据。返回的字符串将显示在Label控件中。
[ConnectionConsumer("Country1","CountryConsumer")]
    public void SetCountry(ICountry provider)
    {
        // 调用提供者的方法接收数据
        string country = provider.GetCountry();
        if (!string.IsNullOrEmpty(country))
        {
            label1.Text = country;
        }
    }

选择WebPartManager控件,在属性编辑器中单击StaticConnection按钮的省略号进行配置连接
ConsumerConnectionPointIDCountryConsumer
ConsumerIDCountry1
IDCountryConnection
ProviderConnectionPointIDCountryProvider
ProviderIDEvent1

用属性配置好连接,会给WebPartManager控件添加<StaticConnection>元素
<asp:WebPartManager ID="WebPartManager1" runat="server">
			<StaticConnections>
				<asp:WebPartConnection ID="CountryConnection" ConsumerConnectionPointID="CountryConsumer"
					ConsumerID="Country1" ProviderConnectionPointID="CountryProvider" ProviderID="Events1">
				</asp:WebPartConnection>
			</StaticConnections>
		</asp:WebPartManager>

启动Web页面,建立了连接后,在Event控件中选择一个值,就会显示在右边的Country控件中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值