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

放肆的年华 提交于 2020-01-15 13:12:28

问题


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 ' />

回答1:


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!



来源:https://stackoverflow.com/questions/32871225/how-do-i-call-a-static-method-on-my-asp-net-page-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!