Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a javascript function before and after button click event call in asp.net

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.

like image 325
sohaib Avatar asked Jan 20 '14 06:01

sohaib


3 Answers

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

like image 52
Akbar Kautsar Avatar answered Sep 28 '22 00:09

Akbar Kautsar


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
    }
}
like image 41
Alvin Avatar answered Sep 28 '22 00:09

Alvin


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.

like image 20
live-love Avatar answered Sep 27 '22 23:09

live-love