简体   繁体   中英

How do I call a static method on my ASP.Net page, from Javascript?

Sorry if this is a simple answer, but I can't seem to find this (on SO or Google.)

I have an aspx page, with a GridView and each record has a button.

What I need to do is execute a bit of Javascript on each record that requests a bit of data from the underlying page class. The method on the class is static, so I'm not interested in the instance.

Also, I want to call this method WITHOUT doing a postback. Can this be done and, if so, how do I do this?

NOTE

I know that everyone always wants the code but, essentially, I'm looking for a snippet that I can put within an OnClientClick event. Something like this:

<asp:Button id="myButton" 
    runat="server" 
    ... 
    OnClientClick='PageClass.UserMustConfirm()?confirm("Are you sure you want to continue?") : true ' />

Like others in the comments have already said, you're going to need to use Ajax or PageMethods...but I wanted to clear up a few misconceptions you may have about how this works in the first place.

There is a clear separation from code that runs in the client vs code that runs in the server -- this is no way for you to call server code directly from client code -- how could there be? Instead, you need to make a request to the server where that code "lives", get the response, and do something meaningful with it in the client -- that is what PageMethods does: it opens up a method as a WebMethod and lets the client code do something seamlessly.

But you shouldn't do that.

Instead of relying on what is basically an ancient framework (WebForms), look into using jQuery's $.ajax(...) and Promise objects to do this for you in a more explicit, framework-agnostic way.

Short answer: you cannot directly call C# from JavaScript that runs (in the browser at least).

Long answer: you can use Ajax to send the server parameters to call C# code with and do something with the returned result.

Hope that helps!

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