Execute ClientSide before ServerSide in ASP.NET
Asked Answered
F

5

0

I am using ASP.NET 3.5.

When the user click on say btnSubmit I want to first execute some JavaScript code and then execute some C#/VB.NET code.

Is this possible? If so how would one do it?

Thanks in advance!

Fairspoken answered 5/8, 2010 at 13:39 Comment(0)
H
1

This is very simple:

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>
Husein answered 5/8, 2010 at 13:44 Comment(0)
M
0

Have the JavaScript execute and then call a web service with xmlhttprequest from the javascript

Msg answered 5/8, 2010 at 13:43 Comment(0)
G
0

Of course, you simply add an onClick event all JS code is executed before the postback.

If the code is for validation and you decide you don't want to submit you can return false and it won't post.

<asp:Button OnClientClick="" />
Gregale answered 5/8, 2010 at 13:44 Comment(0)
M
0

There is onClientClick property - check this out http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

Massy answered 5/8, 2010 at 13:44 Comment(0)
F
0

Thanks for the answer guys!

To execute a function from code behind one would do this in VB.NET

 Protected Sub btnSubmit_Click(blah blah) Handles btnSubmit.Click

    ClientScript.RegisterStartupScript(Me.GetType(), "hiya", "Message()", True)
    lblLabel.Text = "Hello my name is Etienne!"

End Sub
Fairspoken answered 6/8, 2010 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.