javascriptasp.netautopostback

ASP.NET onClientClick return false not working


I want to hide divs on button click and show them on a different button click. Sadly there is always a postback on the image button click. What is causing this problem?

Here is my backend code

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i <= 10; i++)
    {
        HtmlGenericControl divTest = new HtmlGenericControl("div");
        divTest.Attributes.Add("class", "divClass");
        divTest.Attributes.Add("ID", "myDIV");
        divTest.InnerText = "Div" + i;
        form1.Controls.Add(divTest);

        ImageButton collapseButton = new ImageButton();
        collapseButton.ImageUrl = "~/images/minus.png";
        collapseButton.Attributes.Add("OnClientClick", "myHideFunction(); return false;");
        collapseButton.Height = 20;
        collapseButton.Width = 20;
        divTest.Controls.Add(collapseButton);

        ImageButton expandButton = new ImageButton();
        expandButton.ImageUrl = "~/images/plus.png";
        collapseButton.Attributes.Add("OnClientClick", "myShowFunction(); return false;");
        expandButton.Height = 20;
        expandButton.Width = 20;
        form1.Controls.Add(expandButton);
    }
}

And here is my front end code

CSS

<style>
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
</style>

Javascript

<script>

function myShowFunction() {
    var x = document.getElementById("myDIV");
    x.style.display = "block";
}

function myHideFunction() {
    var x = document.getElementById("myDIV");
    x.style.display = "none";
}
</script>

Solution

  • Add onclientclick on button:

    collapseButton.OnClientClick = "return myHideFunction();");
    

    You need to return false from your methods like this:

    <script>
    
    function myShowFunction() {
        var x = document.getElementById("myDIV");
        x.style.display = "block";
        return false;
    }
    
    function myHideFunction() {
        var x = document.getElementById("myDIV");
        x.style.display = "none";
        return false;
    }
    </script>