Stop page reload of an ASP.NET button

15,195

Solution 1

You need to use return statement at two points.

OnClientClick="return jsfunction();"

function jsfunction()
{
  //
  return false;
}

OR, you can return false after the function call like this.

OnClientClick="jsfunction(); return false;"

Note if you want to do postback conditionally then you need to return true or false.

OnClientClick="return jsfunction();"

function jsfunction()
{
  if(conditionForPostBack)
      return true;
  else
      return false;
}

Solution 2

or you can disable the submit behaviour. By default asp.net renders button as submit button. if you disable submit behaviour it will render button as button type

<asp:Button UseSubmitBehavior="false" OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />

But with this code it will not fire server side event "OnClick"

Share:
15,195
user2217039
Author by

user2217039

Updated on June 05, 2022

Comments

  • user2217039
    user2217039 almost 2 years

    NET application, I have inserted a button that call a Javascript function (OnClientClick event) and a VB.NET function (OnClick event)

    <asp:Button OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
    

    The problem is that when I click the button, it refreshes the page and delete the content of the text boxes.

    I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event.

    How can I avoid the page reload ?

    P.S.: At the end of the Javascript function a new window is opened window.open(newWindow.aspx), but I want that the first page mantain the value inserted by the user in the Text Boxes.

    Thanks in advance :)

  • Ian
    Ian almost 11 years
    "I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event."
  • Ian
    Ian almost 11 years
    But it seems that they want to execute the OnClick as well, just without the page reload
  • Ujjwal Manandhar
    Ujjwal Manandhar almost 11 years
    yeah it seems but they have not mentioned it earlier.. :)
  • Ian
    Ian almost 11 years
    I already explained. The OP already used this and it worked, but since the postback is prevented with "return false", it isnt what they want. Im pretty sure theyre looking for AJAX
  • Ujjwal Manandhar
    Ujjwal Manandhar almost 11 years
    Adil's answer will solve the problem if he wants conditional post back
  • user2217039
    user2217039 almost 11 years
    Yes I want to execute the vb.net function.... I have written: "I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event." :)