Web Part 是asp.net 2.0中提供的新特性,通过它可以让最终用户自由修改页面布局,效果可以看看Google的自定义页面http://www.google.com/ig?hl=zh-CN,其使用也非常简单,下面就说一下两个Web part通讯方面的使用心得.

Web part进行通讯是由WebPartManager管理的。
    1。定义一个公共的接口,供通讯使用。
    2。WebPartManager通过发布者得到接口。
    3。WebPartManager传递接口给订阅者。
我做了个通过日历控件取得日期传递到另一个web part中的TextBox的实验,其中出了点问题。先看接口代码

using System;
using System.Data;



public interface ISelectedDate
{

    DateTime SelectedDate();
}

日历作为借口提供者,首先要实现接口,同时要通过 [ConnectionProvider("ISelectedDate", "DateInfoProvider")]来标记。ConnectionProvider中第一个参数为接口名,后一个为传递的参数。代码如下:

public partial class CalendarUC : System.Web.UI.UserControl,ISelectedDate
{
    DateTime _DateInfo 
= DateTime.Now;
    [Personalizable]
    
public DateTime DateInfo
    
{
        
get return _DateInfo; }
        
set { _DateInfo = value; }
    }



    [ConnectionProvider(
"ISelectedDate""DateInfoProvider")]
    
public ISelectedDate GetDate()
    
{
        
return this;
    }

    
public DateTime SelectedDate()
    
{
        
return _DateInfo;
    }

    
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    
{
        _DateInfo 
= this.Calendar1.SelectedDate;

    }




    
protected void Page_Load(object sender, EventArgs e)
    
{

    }

   
}


然后是消息订阅者应使用该消息,它需要通过[ConnectionConsumer("ISelectedDate", "DateInfoConsumer")]标记。代码如下:

public partial class google : System.Web.UI.UserControl
{
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        Response.Write(Page.IsValid);
        
string queryStr=HttpUtility.UrlEncode(TextBox1.Text);
        Response.Redirect(
@"http://www.google.com/search?q=" +queryStr);

    }

    [ConnectionConsumer(
"ISelectedDate""DateInfoConsumer")]
    
public void GetDate(ISelectedDate SearchText)
    
{
       TextBox1.Text
= SearchText.SelectedDate().ToString();

    }

 
}

最后就是通过设置WebPartManager的属性来建立静态的连接。修改以下代码

<asp:WebPartManager ID="WebPartManager1" runat="server">  
        
<StaticConnections>
        
<asp:WebPartConnection ID="DataConnection" Runat="server"
 ProviderID
="CalendarUC2" ProviderConnectionPointID="DateInfoProvider" ConsumerID="Google1" ConsumerConnectionPointID="DateInfoConsumer" />
        
</StaticConnections>  

        
</asp:WebPartManager>

最后就是将WebPartManager的 DisplayMode 设置为WebPartManager.ConnectDisplayMode;
理论上讲,如果完成以上的步骤就应该完成了静态通讯的建立,但运行后发现会报以下错误。
The specified display mode is not supported on this page. Make sure
personalization is enabled and the corresponding zones are present on the
page. The display mode can be set during and after Page_Init.
Parameter name: value

不过再页面上加一个ConnectionZone控件就能解决这个问题,但是这样运行后会让最终用户看见这个ConnectionZone控件,总感觉有更好的办法,能完全通过代码建立连接,希望有好办法的朋友告诉我一下。

posted on 2005-12-21 20:50  圣炎¢天乐  阅读(3704)  评论(15编辑  收藏  举报