1

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!

2 Answers 2

2

The reason for this is you're missing a couple parameters from your PageMethods.Connect() method.

PageMethods.Connect(); will call the function via ajax on the server, but it's asynchronous so you have to specify a callback.

PageMethods.Connect(function(resp){ alert(resp); }, 
                    function(err){ alert(err.get_message()); });

the first callback is called when the server returns with the result without error, the second is called on error.

more information is available at:

Also, don't forget to add the script manager:

<asp:ScriptManager runat="server" EnablePageMethods="true" EnablePartialRendering="true"></asp:ScriptManager>
Sign up to request clarification or add additional context in comments.

Comments

1

Yeah, that's because C# is executed on the server side and javascript is executed on the client side, so when your aspx renders the page, "PageMethods.Connect();" loses its meaning...

But there are ways to do this, with asynchronous requests

See https://en.wikipedia.org/wiki/Ajax_%28programming%29

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.