locked
Calling a c# function from a Javascript method RRS feed

  • 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!

    Wednesday, April 3, 2013 3:43 PM

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

    • Proposed as answer by chilberto Wednesday, April 3, 2013 9:44 PM
    • Marked as answer by Eclectica Thursday, April 4, 2013 8:59 AM
    Wednesday, April 3, 2013 9:44 PM

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

    • Proposed as answer by chilberto Wednesday, April 3, 2013 9:44 PM
    • Marked as answer by Eclectica Thursday, April 4, 2013 8:59 AM
    Wednesday, April 3, 2013 9:44 PM
  • 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

    Thursday, April 4, 2013 4:29 AM