javascript ASP.NET 从 JS AJAX 调用非静态 webmethod
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14500136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET calling non-static webmethod from JS AJAX
提问by user829174
Possible Duplicate:
Call non-static method in server side(aspx.cs) from client side use javascript (aspx)
I have this following code that is working fine
我有以下工作正常的代码
function getFooObj() {
$.ajax({
type: "POST",
url: "Dummy.aspx/GetFooObj",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('good');
}
});
}
[WebMethod]
public static FooObj GetFooObj ()
{
// some code that returns FooObj
}
my question is if i want my WebMethod NOT to be static, how can i call it from JS?
我的问题是,如果我希望我的 WebMethod 不是静态的,我该如何从 JS 调用它?
[WebMethod]
public FooObj GetFooObj ()
{
// some code that returns FooObj
}
回答by VinayC
Not possible - PageMethods has to be static.
不可能 - PageMethods 必须是静态的。
Reason is quite simple - a instance (non-static) method means it can access page state including controls. However, ASP.NET page/control model needs state information (view-state, event validation etc) for ensuring consistent state of controls. But in case of Page Methods, this is not possible because complete form is not posted back (which is essentially the idea behind PageMethods/ScriptServices - you send/receive only bare minimum information between client/server).
原因很简单——一个实例(非静态)方法意味着它可以访问页面状态,包括控件。但是,ASP.NET 页面/控件模型需要状态信息(视图状态、事件验证等)以确保控件的状态一致。但是在 Page Methods 的情况下,这是不可能的,因为不会回发完整的表单(这本质上是 PageMethods/ScriptServices 背后的想法 - 您仅在客户端/服务器之间发送/接收最少的信息)。
For using instance methods (assuming that you need control access), you should use UpdatePanel way of doing AJAX.
对于使用实例方法(假设您需要控制访问),您应该使用 UpdatePanel 执行 AJAX 的方式。
回答by AshokD
The reason it supports only static methods is that page is instantiation is not done, if you want to use non static web methods then go for web service(.asmx).
它只支持静态方法的原因是页面没有完成实例化,如果你想使用非静态 web 方法,那么去 web service(.asmx)。

