gruber
gruber

Reputation: 29729

Run a Javascript function before postback

On my ASPX page, there is a button with this code:

OnClick="save_Click"

Is it possible to execute Javascript before postback and if the result is true, then do the postback and go to method save_click?

Upvotes: 8

Views: 8127

Answers (4)

Sjoerd
Sjoerd

Reputation: 75599

I changed the definition of the __doPostback function to accomplish this:

<script type="text/javascript">
    var originalDoPostback = __doPostBack;
    __doPostBack = function (p1, p2) {
        doSomethingCustomHere();
        originalDoPostback(p1, p2);
    };
</script>

Upvotes: 1

The_Butcher
The_Butcher

Reputation: 2488

There is a property called "OnClientClick" as well. Here you can specify a function that will validate (I'm guessing), or just run regular javascript.

If your data is not valid you can just return false; from the method. That should cancel your postback

Upvotes: 7

ashish.chotalia
ashish.chotalia

Reputation: 3746

http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx

<%@ Page Language="C#" %>
<script runat="server">
    protected void Button1_Click(Object sender, EventArgs e)
    {
        Label1.Text = "Server click handler called.";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
  <form id="form1" runat="server">
    <asp:Button ID="Button1" Runat="server" 
      OnClick="Button1_Click" 
        OnClientClick="return confirm('Ready to submit.');" 
        Text="Test Client Click" />
    <br />
    <asp:Label ID="Label1" Runat="server" text="" />
  </form>
</body>
</html>

Possible duplicate of : Execute ClientSide before ServerSide in ASP.NET

Upvotes: 1

Davide Piras
Davide Piras

Reputation: 44605

you should use the very well known way: return confirm('bla bla bla')

adding this snippet to the onclick attribute of the button in the page or button prerender method, server side...

Upvotes: 1

Related Questions