Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Javascript function before postback

Tags:

c#

.net

asp.net

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?

like image 345
gruber Avatar asked Feb 15 '11 10:02

gruber


4 Answers

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

like image 108
The_Butcher Avatar answered Nov 04 '22 17:11

The_Butcher


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...

like image 30
Davide Piras Avatar answered Nov 04 '22 19:11

Davide Piras


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

like image 44
ashish.chotalia Avatar answered Nov 04 '22 18:11

ashish.chotalia


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>
like image 1
Sjoerd Avatar answered Nov 04 '22 17:11

Sjoerd