问题
If I have, say, an .aspx page that has a button called "btnProcess":
asp:imagebutton id="btnProcess" onmouseover="src='siteart/addpayment2.gif'" tabIndex="13" onmouseout="src='siteart/addpayment1.gif'" Runat="server" Width="88" Height="22" ImageUrl="siteart/addpayment1.gif" AlternateText="Add Payment Button (CTRL + Plus(+))"
With jQuery, if I wanted to link a function to that button when it's pressed, I could write something like this:
$(document).ready(function () {
$('#btnProcess').click(function () {
return validateFields();
});
});
If validateFields()
returns False
, the code behind:
Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnProcess.Click
will not fire. Vice versa if validateFields()
returns True
If I comment out return validateFields();
the code behind will fire - if I never declare a function that will trigger on click with javascript, the code behind will fire (these scenarios makes sense)
My question is (and I may be asking it wrong, sorry in advance) why can the javascript button.click function prevent the code behind from firing when it returns false?
I've always learned to think of client-side and server-side code as individual pieces of logic that really don't intertwine like this.
I'm looking for something more than "just because" which is what I received from a coworker.
回答1:
The ASP.NET postback is done by a JavaScript function called __doPostBack
, if you view the source of your page it looks like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
Note: If you have ever had to determine which control caused a postback, then the __EVENTTARGET
name should look familiar. In your code-behind you would get the name of the control which caused the postback like this: Page.Request.Params.Get("__EVENTTARGET");
As you can see this submits the form to the server, which is what we call a postback.
Using return false;
or event.preventDefault()
short-circuits the call to __doPostBack
and your postback doesn't happen.
来源:https://stackoverflow.com/questions/18002368/how-the-javascript-event-function-can-prevent-server-side-event-function-button