i have created "ButtonClick" function in ASP.NET as following:
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click"/>
i want to know, is it possible to call a javascript function before and after calling asp.net button click function...???
Thanks.
Yes it's possible, here is quick example: Java script function to call.
<script type="text/javascript">
function clientValidate() {
alert("execute before");
return true;
}
function executeAfter() {
alert("execute after");
}
</script>
Here is snapshoot for button
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="clientValidate()" onclick="btnLogin_Click"/>
Notice property onClientClick="clientValidate()", it will be trigger script before button click on the server.
On the server side:
protected void btnLogin_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>executeAfter();</script>", false);
}
Notice executeAfter();, it will trigger javascript execution after server event.
Don't forget to place <asp:ScriptManager runat="server"></asp:ScriptManager>
in your aspx file.
Hope it help
put this on your page and make sure you have a scriptmanager. these codes will handle your pre & post postbacks.
var prm, postBackElement;
if (typeof Sys != "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, e) {
postBackElement = e.get_postBackElement();
if (postBackElement.id == "btnLogin") {
// before click codes
}
}
function EndRequest(sender, e) {
if (postBackElement.id == "btnLogin") {
// after click codes
}
}
Before:
<script type="text/javascript">
function executeBefore() {
alert("execute before");
}
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="executeBefore()" onclick="btnLogin_Click"/>
After:
<script type="text/javascript">
function executeAfter() {
alert("execute after ");
}
</script>
Add this code to your server side event:
Page.ClientScript.RegisterStartupScript(GetType(), "none", "<script>executeAfter();</script>", false);
If you don't have a master page, or are not using ajax, there is no need to add ScriptManager.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With