Stop page reload of an ASP.NET button

2019-07-23 17:22发布

问题:

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 :)

回答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;
}


回答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"



回答3:

if you are not going to trigger the button with C# Codebehind function, then you dont need to use asp:Button. Therefore you can use a regular html .

<button id='btn_1' onclick='ajax_function()'>Button</button>

html button is much easier and faster. if you use asp:button, then you should use clientid() function to catch the control to trigger the ajax.