从JavaScript调用ASP.NET页面方法无法工作。

9

你好,我正在从JavaScript调用一个简单的页面方法,这是我的标记代码:

 function OnCallSumComplete(result, userContext, methodName) {             
            alert(result);
 }
 function OnCallSumError(error, userContext, methodName) {
     if (error !== null) {
         alert(error.get_message());
     }
 }
 function test(){
     var contextArray = "";
     PageMethods.TestMethod("test parameter", OnCallSumComplete, OnCallSumError,  contextArray);
 }

 <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />

at cs

 [System.Web.Services.WebMethod]
 public static string TestMethod(string para)
 {

    return "Yes this is working";
 }

警报显示结果并说“null”。我检查了Firebug,没有从控制台看到错误。
如果我将TestMethod更改为
 [System.Web.Services.WebMethod]
 public static string TestMethod()
 {
    return "Yes this is working";
 }

并且PageMethod

 PageMethods.TestMethod( function (response) { alert(response);  } );

它显示了正确的响应为“Yes this is working”。然而,我需要向函数传递参数。我有什么遗漏吗?

感谢您的帮助。

4个回答

3

我认为主要问题出在您所使用的ScriptManager组件上。

<asp:ScriptManager ID="ScriptManager1" 
                   EnablePageMethods="true" 
                   runat="server" />

为解决您的问题,请在Webconfig中使用以下内容 -
<pages>
  <controls>
    <add tagPrefix="ajax" 
         namespace="System.Web.UI" 
         assembly="System.Web.Extensions, 
                   Version=1.0.61025.0, 
                   Culture=neutral, 
                   PublicKeyToken=31bf3856ad364e35"/>
  </controls>
</pages>

在您的.aspx页面中使用以下行 -
<ajax:ScriptManager ID="ScriptManager1" 
                    EnablePageMethods="true" 
                    runat="server" />

希望这能帮助你解决问题。

2

我认为你需要使用[ScriptMethod]来代替或者补充[WebMethod],这样才能通过javascript调用asmx方法。之所以可能在不带参数的情况下也能工作,是因为请求在处理该方法时不需要解析任何内容。

尝试使用[ScriptMethod](并可能在类定义上使用[ScriptService])看看是否有所不同。


嗨,我尝试使用[System.Web.Script.Services.ScriptMethod],但是在firebug控制台中出现了错误“PageMethods未定义”。 - windforceus
你也添加了 ScriptService 吗?如果该类不再定义,那么可能是定义类接口的 JavaScript 文件未加载。尝试查看网络选项卡,看看是否有任何 404 错误。 - RTigger
我得到了编译错误。"属性'System.Web.Script.Services.ScriptService'在此声明类型上无效。它只在'class,interface'声明上有效。" - windforceus
我使用WebMethod和ScriptMethod,在Firebug中,我可以看到响应是{"d":"Yes this is working"}。页面似乎将值分配给“d”,但我不知道如何从“d”中检索值。 - windforceus
这就是 asp.net ajax web 服务发送信息的方式,它们将响应包装在一个名为“d”的对象属性中。您可以在此处阅读更多信息:http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/。虽然很高兴它对您有用。 - RTigger

1
问题在于您的Web.config文件中需要启用一个模块(IHttpModule):ScriptModule-4.0。它默认是启用的,但您可能已将其删除。如果您有兴趣,请查看机器范围的Web.config文件,并查看它是否已从本地Web.config文件中删除。它的声明应该位于system.webServer/modules(对于IIS >=7)和system.web/httpModules(对于Visual Studio内置的Web服务器或IIS <7)下。

0

据我所记,您在调用时只需要3个参数(您的参数、onsuccess和onfailure)。您尝试使用PageMethods.TestMethod("test parameter", OnCallSumComplete, OnCallSumError)了吗?


是的,我试过了,但仍然收到“null”消息。感谢您的回复。 - windforceus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接