如何从Javascript调用ASP.Net页面上的静态方法? [英] How do I call a static method on my ASP.Net page, from Javascript?

查看:56
本文介绍了如何从Javascript调用ASP.Net页面上的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是一个简单的答案,但我似乎找不到(在SO或Google上).

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

我有一个aspx页面,带有GridView,每个记录都有一个按钮.

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

我需要做的是在每个记录中执行一些Javascript,以从基础页面类中请求一些数据.该类上的方法是静态的,因此我对该实例不感兴趣.

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?

注意

我知道每个人都一直想要代码,但从本质上讲,我正在寻找可以放在 OnClientClick 事件中的代码段.像这样:

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

推荐答案

就像评论中的其他人已经说过的那样,您将需要使用Ajax或PageMethods ...但是我想清除一些误解可能首先了解它的工作原理.

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.

与在客户端中运行的代码与在服务器中运行的代码有明显的区别-这无法让您直接从客户端代码中调用服务器代码-怎么可能?相反,您需要向该代码存在"的服务器发出请求,获取响应,并在客户端中对其进行有意义的操作-这就是 PageMethods 的作用:它将打开一个方法作为 WebMethod ,并允许客户端代码无缝地执行某些操作.

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.

但是你不应该那样做.

与其使用基本的古老框架(WebForms),还不如使用jQuery的 $.ajax(...) Promise 对象来实现此目的您以更明确,与框架无关的方式来访问您.

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.

简短的回答:您不能直接从运行的JavaScript(至少在浏览器中)调用C#.

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

长答案:您可以使用Ajax发送服务器参数来调用C#代码,并对返回的结果进行处理.

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

希望有帮助!

这篇关于如何从Javascript调用ASP.Net页面上的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆