【问题标题】:Asp.net UserControl Implement OnClientClick EventAsp.net UserControl 实现 OnClientClick 事件
【发布时间】:2013-11-12 21:34:13
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

    • 我已经使用反射器查看过它... this.ViewState["OnClientClick"] = value;我在二传手中找到了,但我仍在寻找我需要的其他东西
    • 按钮控件覆盖 AddAttributesToRender 事件。
    • 有没有办法在 UserControl 中做到这一点?
    • UserControl 没有 AddAttributesToRender,因为它可以有多个控件。换句话说,将客户端onclick事件添加到SqlDataSource是没有意义的。这完全取决于您在 UserControl 中放置的控件。如果您开始操作所有这些事件,您可能需要查看自定义服务器控件。
    【解决方案2】:

    你可以这样写:

    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);
    }
    

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

    【讨论】:

      【解决方案3】:

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

      <asp:AwsomeUserControl ClientID="myUserControl" />
      

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

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

      【讨论】:

      • 对不起,我希望代码像按钮一样应用到服务器端
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多