简体   繁体   中英

Calling a c# function from a Javascript method

I'm trying to call ac# 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!

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM