上一篇介紹了Web Parts基礎,如果兩個Web Part之間不能通訊,那就相當郁悶的,所以Asp.Net提供了兩種方式來使得Web Part之間可以互相通訊,一種是靜態通訊方式,另一種時使用ConnectionZone進行動態通訊。(這里所謂的“Web Part通訊”是指多個WebPart中用戶控件之間的通訊)。下面是Web Parts直接進行通訊的模型:
我在學習過程中,通過實例--根據我的Blog的RSS來搜索文章--來演示Web Part之間的靜態通訊。運行結果如下所示(沒有進行界面美化^_^):
起始頁面:
以"struct"作為關鍵字搜索的結果頁面:
頁面中放了兩個Web Part,第一個WebPart中包含一個由文本框和按鈕組成的用戶控件Search(這里用的是用戶控件,而不是直接在WebPart放置文本框和按鈕,如果直接放的話每個控件都有個標題條TitleBar,感覺太別扭);第二個WebPart中負責顯示搜索結果,也是包含一個用戶控件Content,Content控件包含0個或多個動態添加的Label。下面是設計Web Parts間進行通訊的步驟:
1. 創建消息接口:定義一個IMessage接口
public interface IKeyWord2
{3
string Message{ get;}4
}
2. 通訊提供者(Provider):
這個示例中,第一個WebPart中的用戶控件Search作為通訊提供者,因此我們定義Search控件的代碼如下:
public partial class Search : System.Web.UI.UserControl,IKeyWord//繼承通訊接口IKeyWord2
{3
protected void Page_Load(object sender, EventArgs e)4
{5
}6

7
/*通訊提供者,實現方法返回消息接口,并且方法上要運用特性[ConnectionProvider],第二個參數用作在WebPartManager中注冊*/8
[ConnectionProvider("KeyWord", "KeyWordProvider")]9
public IKeyWord KeyWordProvide()10
{11
return this;12
}13

14
IKeyWord 成員20
}21

22

3. 通訊訂閱者(Consumer):
這個示例中,第而個WebPart中的用戶控件Content作為消息訂閱者,因此我們定義該控件的代碼如下:
public partial class Content : System.Web.UI.UserControl2
{ 3
protected void Page_Load(object sender, EventArgs e)4
{5
}6

7
[ConnectionConsumer("KeyWord","KeywordConsumer")]8
public void GetKeyWord(IKeyWord keyword)9
{10
ProcessRSSItem(keyword.Message);11
}12

13
//解析RSS,并顯示解析結果14
public void ProcessRSSItem(string keyword)15
{16
System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument();17
rssDoc.Load(Server.MapPath("source.xml"));18
System.Xml.XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");19

20
string title = "";21
string link = "";22
string description = "";23

24
for (int i = 0; i < rssItems.Count; i++)25
{26
System.Xml.XmlNode rssDetail;27

28
//讀取標題29
rssDetail = rssItems.Item(i).SelectSingleNode("title");30
if (rssDetail != null)31
title = rssDetail.InnerText;32
else33
title = "";34

35
//如果不包括keyword關鍵字,則跳轉到下一條記錄36
if (!String.IsNullOrEmpty(keyword) && (title.IndexOf(keyword) == -1))37
continue;38

39
//讀取URL40
rssDetail = rssItems.Item(i).SelectSingleNode("link");41
if (rssDetail != null)42
link = rssDetail.InnerText;43
else44
link = "";45

46
//讀取描述信息47
rssDetail = rssItems.Item(i).SelectSingleNode("description");48
if (rssDetail != null)49
description = rssDetail.InnerText;50
else51
description = "";52

53
//輸出 54
Label label = new Label();55
label.Text = "<p><b><a href='" + link + "' target='new'>" + title + "</a></b><br/>" + description + "</p>";56
this.Controls.Add(label);57
}58
}59
}60

61

4. 在頁面*.aspx的WebPartManager中注冊提供者和訂閱者:
<asp:WebPartManager ID="wpManager" runat="server">2
<StaticConnections>3
<asp:WebPartConnection ID="KeywordConnection"4
ProviderID="search" ProviderConnectionPointID="KeyWordProvider"5
ConsumerID="content" ConsumerConnectionPointID="KeywordConsumer">6
</asp:WebPartConnection>7
</StaticConnections>8
</asp:WebPartManager>
附:完整源碼下載https://files.cnblogs.com/happyhippy/WebPartDemo.rar


浙公網安備 33010602011771號