Answered by:
Calling a c# function from a Javascript method

Question
-
I'm trying to call a c# function from a javascript function:
In my default.aspx I have following code: (javascript)<script type="text/javascript"> function App() { var temp; temp = PageMethods.Connect(); alert(temp); } </script>
(HTML)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <div class="menuContent"> <p><a href="#" onclick="App();">blabla!</a></p> <div id="navTreeContainer"> <div id="navtree"></div> </div> </div> </asp:Content>
Default.aspx.cs
[WebMethod] public static string Connect() { string test; test = "test"; return test; }
When I try this out nothing happens.I don't know what I do wrong here...
Someone that can help me please ?
Thanks!
Answers
-
It could be you are missing the scriptmanager reference:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
You also will need to rework you javascript as the generated javascript is expecting a function to be passed as a callback:
<script type="text/javascript"> function App() { PageMethods.Connect(callback); } function callback(val) { alert(val); } </script>
Hope this helps!Jeff
All replies
-
It could be you are missing the scriptmanager reference:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
You also will need to rework you javascript as the generated javascript is expecting a function to be passed as a callback:
<script type="text/javascript"> function App() { PageMethods.Connect(callback); } function callback(val) { alert(val); } </script>
Hope this helps!Jeff
-
The javascript will run on the client and the c# code runs on the server - eg these pieces are not on the same computer. You can't just call one from the other.
You can write javascript to create and execute an AJAX style call which will create a web request and then catch the response. jQuery has some nice helpers for this.
Paul Linton