向web控件添加html属性,事件
对于自定义控件可用System.Web.UI.HtmlTextWriter的以下两个方法之一:
a.AddAttribute():用于将title,class,style和onclick等html属性添加到html元素
b.AddStyleAttribute():用于将样式设置添加到html元素,如background-color,color和font-size等。
---------------------------------如以下为一个自定义控件ConfirmButton----------------
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace ClientSideScript
{
/// <summary>
/// ConfirmButton 的摘要说明。
/// </summary>
[DefaultProperty("PopupMessage"),
ToolboxData("<{0}:ConfirmButton runat=server></{0}:ConfirmButton>")]
public class ConfirmButton : Button
{
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public string PopupMessage
{
get
{
// 检查 ViewState 中是否存在该项目
object popupMessage = this.ViewState["PopupMessage"];
if (popupMessage != null)
return this.ViewState["PopupMessage"].ToString();
else
return "真的要删除吗?";
}
set
{
// 指定 ViewState 变量
ViewState["PopupMessage"] = value;
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
string script = @"return confirm(""%%POPUP_MESSAGE%%"");";
script = script.Replace("%%POPUP_MESSAGE%%",
this.PopupMessage.Replace("/"", "///""));
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, script);
}
}
}
在web页面中加入以上控件,只要点击控件就可以弹出一个显示有PopupMessage信息的对话框。
对于一般的web控件(如Button)可以直接用以下的程式加入html属性:
如:private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
string script = @"return confirm('真的要删除吗?');";
this.Button1.Attributes.Add("onclick",script);
}
其他方法:用添加脚本块的方法
如下程序
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace ClientSideScript
{
[DefaultProperty("PopupMessage"),
ToolboxData("<{0}:PopupGreeting runat=server></{0}:PopupGreeting >")]
public class PopupGreeting : System.Web.UI.Control
{
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public string PopupMessage
{
get
{
object popupMessage = this.ViewState["PopupMessage"];
if (popupMessage != null)
return this.ViewState["PopupMessage"].ToString();
else
return "Welcome to my Web site!";
}
set { ViewState["PopupMessage"] = value; }
}
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public bool Enabled
{
get
{
object enabled = this.ViewState["Enabled"];
if (enabled != null)
return (bool) this.ViewState["Enabled"];
else
return true;
}
set
{
ViewState["Enabled"] = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string scriptKey = "intoPopupMessage:" + this.UniqueID;
if (!Page.IsStartupScriptRegistered(scriptKey) && this.Enabled &&
!Page.IsPostBack)
{
string scriptBlock =
@"<script language=""JavaScript"">
<!--
alert(""%%POPUP_MESSAGE%%"");
// -->
</script>";
scriptBlock = scriptBlock.Replace("%%POPUP_MESSAGE%%", this.PopupMessage);
Page.RegisterStartupScript(scriptKey, scriptBlock);
}
}
}
}