在.Net Web应用程序开发中, 我们希望用户在做一个重要的操作时, 能够询问或警告用户. 或者希望我们有这么一个简单实用的控件, 能在用户确定后引发一个服务端的事件.
这个控件的原理很简单,主要是实现IPostBackEventHandler接口和调用Page.GetPostBackEventReference(this, eventArgument), 实现对客户端__doPostBack方法的调用, 引发服务端的事件
而以下这段关键代码是实现功能的核心:
if(AlertString != "") //仅在用户确认后调用客户端的__DostPostBack, 引发服务端事件
{
Action = "javascript:if(window.confirm(\'" + AlertString + "')==true){";
Action += Page.GetPostBackEventReference(this, "Click");
Action += ";}";
}
全部代码:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace Booksir.WebControls
{
/// <summary>
/// AlertButton 的摘要说明。
/// </summary>
[
DefaultProperty("Text"),
ToolboxData("<{0}:AlertButton runat=server></{0}:AlertButton>"),
System.ComponentModel.DefaultEvent("Click"),
]
public class AlertButton : System.Web.UI.WebControls.WebControl, IPostBackEventHandler
{
private ViewStateBag StateBag;
public AlertButton()
{
StateBag = new ViewStateBag(this.ViewState);
}
public event EventHandler Click; //事件句柄
public enum AppearanceEnum
{
Button,
ImageButton,
}
/// <summary>
/// 按钮的外观模式
/// </summary>
[
Bindable(false),
Category("Appearance"),
DefaultValue(AppearanceEnum.Button),
Description("按钮的外观模式"),
]
public AppearanceEnum Appearance
{
get
{
object obj;
obj = ViewState["Appearance"];
if(obj == null)
{
Appearance = AppearanceEnum.Button;
return AppearanceEnum.Button;
}
return (AppearanceEnum)obj;
}
set
{
ViewState["Appearance"] = value;
}
}
/// <summary>
/// 在DefaultValue为非常量值的情况下,可以用Reset...来重置属性的默认值
/// </summary>
void ResetAppearance()
{
Appearance = AppearanceEnum.Button;
}
/// <summary>
/// 该方法的存在使系统在属性为默认值不提交属性赋值代码
/// </summary>
/// <returns></returns>
bool ShouldSerializeAppearance()
{
return Appearance != AppearanceEnum.Button;
}
[
Bindable(true),
Category("Appearance"),
DefaultValue("")
]
public string Text
{
get
{
return StateBag.GetString("Text", this.ID);
}
set
{
ViewState["Text"] = value;
}
}
/// <summary&g