日期:2014-05-20 浏览次数:20447 次
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
using System; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; public partial class WebUserControl : System.Web.UI.UserControl, IPostBackEventHandler { public string TargetID { get; set; } public event EventHandler<EventArgs> Click; public void RaisePostBackEvent(string eventArgument) { if (this.Click != null) this.Click(this, EventArgs.Empty); } protected void Page_PreRender(object sender, EventArgs e) { var ctl = this.Parent.FindControl(this.TargetID); var script = this.Page.ClientScript.GetPostBackEventReference(this, string.Empty); if (ctl is HtmlControl) ((HtmlContainerControl)ctl).Attributes["onclick"] = script; else if (ctl is WebControl) ((WebControl)ctl).Attributes["onclick"] = script; else if(ctl is WebUserControl) ((WebUserControl)ctl).Attributes["onclick"] = script; } }
:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <div runat="server" id="myDiv"> click me </div> <uc1:WebUserControl ID="WebUserControl1" runat="server" TargetID="myDiv" OnClick="myDiv_Clicked" /> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>
using System; using System.Web.UI; public partial class _Default : System.Web.UI.Page { protected void myDiv_Clicked(object sender, EventArgs e) { ScriptManager.RegisterStartupScript(this, this.GetType(), this.GetHashCode().ToString(), "alert('点击了myDiv');", true); } }