javascriptasp.netonclientclick

OnClientClick javascript does not rendered for asp disabled button


<asp:TemplateField HeaderText="Desc" ItemStyle-CssClass="btnDesc">
  <ItemTemplate>
    <asp:Button ID="btn_desc" runat="server" 
         Enabled="<%# ProcessDescButton() %>" 
         Text="<%# ProcessDescText() %>" 
         OnClientClick="ButtonDescAndNotesClick(this);return false;"  />
  </ItemTemplate>
  <HeaderStyle Width="6%" HorizontalAlign="Center" />
  <ItemStyle Width="6%" HorizontalAlign="Center" />
</asp:TemplateField>

This code when rendered in client does not show OnClientClick when ProcessDescButton() method returns FALSE. It only only shows OnClientClick if ProcessDescButton() it returns TRUE!

I have been through different posts regarding the same issue and replaced Enabled attribute of asp:Button to generic HTML attribute "DISABLED". That works but I need to enable and disable the button based on some logic implemented in ProcessDescButton().

I am not sure what to write to make the button enabled. Disabling works if i return "disabled" from ProcessDescButton().


Solution

  • This issue is caused by the behavior of AddAttributesToRender in the Button class, and is different than a LinkButton.

    When Enabled = False, the value of OnClientClick is effectively ignored, and not rendered to the client.

    One option is to disable the button using javascript in document.load on the client.

    Page_PreRender(object sender, EventArgs e)
    {
      string script = @"document.getElementById('{0}').disabled = false;";
      script = string.Format(script, btnTest.ClientID);
      Page.ClientScript.RegisterStartupScript(GetType(), "btnTest_Disable", script, true);
    }
    

    If you're going to be doing a lot of that. I'd recommend sub-classing Button and overriding AddAttibutes to render to get the behavior you want.