1 IPostBackDataHandler 获取自动加载回发数据而必须实现的方法。
定义 ASP.NET 服务器控件为自动加载回发数据而必须实现的方法。
名称 | 说明 | |
LoadPostData | 当由某个类实现时,它为 ASP.NET 服务器控件处理回发数据。 | |
RaisePostDataChangedEvent | 当由类实现时,它用信号要求服务器控件对象通知 ASP.NET 应用程序该控件的状态已更改。 |
2 示例
2.1 CustomerTextBoxError:此事列演示由于无法获取http 协议post过来的name,value 键值对数据而无法保存控件的状态
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.UI;
namespace AspnetEssential.CustomerControl
{
/// <summary>
/// 自定义CustomerTextBoxError控件
/// </summary>
/// <remarks>
/// 不是现IPostBackDataHandler,没法获取自动post的数据
/// </remarks>
public class CustomerTextBoxError:Control
{
/// <summary>
/// 文本改变事件
/// </summary>
/// <summary>
/// 文本
/// </summary>
public string Text
{
get
{
return ViewState["_Text"] as string;
}
set
{
ViewState["_Text"] = value;
}
}
/// <summary>
/// 呈现
/// </summary>
/// <param name="writer"></param>
protected override void Render(HtmlTextWriter writer)
{
//write html tag <input type='text' name='ClientID' value='Text'></>
writer.AddAttribute(HtmlTextWriterAttribute.Name , this.ClientID);
writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
}
}
}
2.2 CustomerTextBox:实现IPostBackDataHandler,从而获取post过来的数据,从而可以保留控件的状态,以及引发文本改变事件。
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.UI;
namespace AspnetEssential.CustomerControl
{
/// <summary>
/// 自定义TextBox控件
/// </summary>
/// <remarks>
/// 学习IPostBackDataHandler的使用
/// </remarks>
public class CustomerTextBox:Control,IPostBackDataHandler
{
/// <summary>
/// 文本改变事件
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// 文本
/// </summary>
public string Text
{
get
{
return ViewState["_Text"] as string;
}
set
{
ViewState["_Text"] = value;
}
}
#region IPostBackDataHandler 成员
public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
string postDataValue=postCollection[postDataKey ];
if (postDataValue!=null && !postDataValue.Equals(Text))
{
Text = postDataValue;
return true ;
}
else
{
return false ;
}
}
public void RaisePostDataChangedEvent()
{
if(TextChanged!=null)
{
EventArgs e=new EventArgs ();
TextChanged(this, e);
}
}
/// <summary>
/// 呈现
/// </summary>
/// <param name="writer"></param>
protected override void Render(HtmlTextWriter writer)
{
//write html tag <input type='text' name='%ClientID%' value='%Text%'></>
writer.AddAttribute(HtmlTextWriterAttribute.Name , this.ClientID);
writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
}
#endregion
}
}
3 实现IPostBackDataHandler 控件
TextBox, HtmlInputText, CheckBox, HtmlSelect, DropDownList 等