Asp.net UserControl实现OnClientClick事件

时间:2013-11-12 21:34:13

标签: c# javascript asp.net custom-controls

我想创建一个自定义的clientide(OnClientClick)事件,我可以在asp.net页面的标记中订阅,就像框架中包含的普通asp.net控件一样。有没有人知道有任何好的例子或教程来展示如何使用用户控件执行此操作?

假设我的用户控件名为AwsomeUserControl.ascx

 <asp:AwsomeUserControl OnclientClick='javascript:
   alert('Hello I am a client side alert from a custom control')'/>

3 个答案:

答案 0 :(得分:2)

它基本上将给定的字符串值呈现给客户端。

public partial class AwsomeUserControl : System.Web.UI.UserControl
{
    public string OnClientClick { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (!string.IsNullOrWhiteSpace(OnClientClick))
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "script", 
            OnClientClick, true);
        }
    }
}

然而,实际的ASP.Net Button控件的OnClientClick事件远不止于此。您可以使用Reshaper或一些反编译工具查看它们。

这是源代码 -

/// Adds the attributes of the <see cref="T:System.Web.UI.WebControls.Button"/> control to the output stream for rendering on the client.
/// </summary>
/// <param name="writer">An <see cref="T:System.Web.UI.HtmlTextWriter"/> that contains the output stream to render on the client. </param>
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
    bool useSubmitBehavior = this.UseSubmitBehavior;
    if (this.Page != null)
        this.Page.VerifyRenderingInServerForm((Control)this);
    if (useSubmitBehavior)
        writer.AddAttribute(HtmlTextWriterAttribute.Type, "submit");
    else
        writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
    PostBackOptions postBackOptions = this.GetPostBackOptions();
    string uniqueId = this.UniqueID;
    if (uniqueId != null && (postBackOptions == null || postBackOptions.TargetControl == this))
        writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueId);
    writer.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);
    bool isEnabled = this.IsEnabled;
    string firstScript = string.Empty;
    if (isEnabled)
    {
        firstScript = Util.EnsureEndWithSemiColon(this.OnClientClick);
        if (this.HasAttributes)
        {
            string str = this.Attributes["onclick"];
            if (str != null)
            {
                firstScript = firstScript + Util.EnsureEndWithSemiColon(str);
                this.Attributes.Remove("onclick");
            }
        }
        if (this.Page != null)
        {
            string backEventReference = this.Page.ClientScript.GetPostBackEventReference(postBackOptions, false);
            if (backEventReference != null)
                firstScript = Util.MergeScript(firstScript, backEventReference);
        }
    }
    if (this.Page != null)
        this.Page.ClientScript.RegisterForEventValidation(postBackOptions);
    if (firstScript.Length > 0)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, firstScript);
        if (this.EnableLegacyRendering)
            writer.AddAttribute("language", "javascript", false);
    }
    if (this.Enabled && !isEnabled && this.SupportsDisabledAttribute)
        writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
    base.AddAttributesToRender(writer);
}

答案 1 :(得分:1)

你可以这样写:

protected void print_click(object sender,eventargs e)
{
  //when i click this button i need to call javascript function
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script language="'javascript'">");
            sb.Append(@"example();");
            sb.Append(@"</script>");
     System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "JCall1", sb.ToString(), false);
}

可以使用ScriptManager.RegisterStartupScript执行JavaScript 此链接可能很有用:Example: How to execute javascript in C#

答案 2 :(得分:0)

为您的用户控件提供客户端ID并使用它,例如:

<asp:AwsomeUserControl ClientID="myUserControl" />

使用jQuery,您可以轻松处理其上的点击事件:

$('#myUserControl').on('click', function(){
    alert('hello from my user control click!');
});