PageMethods在javascript中作为函数的返回

时间:2012-05-29 10:39:17

标签: c# javascript asp.net pagemethods

javascript:

            var Enabled = false;
            function GateWay_Enabled(GateWay_Name) {
                PageMethods.GateWay_Enabled(GateWay_Name, onRequestComplete, onError);
                return Enabled;
            }

            function onRequestComplete(result) {
                Enabled = result;
            }
            function onError(result) {
                alert('Error');

            }
            var MyVariable = GateWay_Enabled('GateWay_Name');

服务器端代码(C#):

[WebMethod]
[ScriptMethod]
public static bool GateWay_Enabled(string GateWay_Name)
{
    bool Enabled = true;
    return Enabled;
}

为什么MyVariable总是假的?
是否有另一种方法可以将PageMethods.GateWay_Enabled(GateWay_Name, onRequestComplete, onError);写为GateWay_Enabled函数的返回值? 我正在寻找这样的东西:

var MyBoolVariable =
bool.parse(PageMethods.GateWay_Enabled(GateWay_Name,
onRequestComplete, onError));

编辑1:
一切正常,PageMethods没有错误 脚本管理器中的EnablePageMethods为true。

编辑2:
我不能将MyVariable放在onRequestComplete()函数中 我制作MyVariable使我的代码更容易 MyVariable的真正代码是:

    GateWays = [
                        { "Cod": 1, "Enabled": GateWay_Enabled('1') },
                        { "Cod": 2, "Enabled": GateWay_Enabled('2') },
                        { "Cod": 3, "Enabled": GateWay_Enabled('3') },
                        { "Cod": 4, "Enabled": GateWay_Enabled('4') },
                        { "Cod": 5, "Enabled": GateWay_Enabled('5') },
                        { "Cod": 6, "Enabled": GateWay_Enabled('6') },
                        { "Cod": 7, "Enabled": GateWay_Enabled('7') }
                ];

我想在另一个地方使用这个数组 我不能把它放在onRequestComplete()函数中 我该怎么办?

4 个答案:

答案 0 :(得分:2)

您需要重新考虑代码。现在你在GateWay_Enabled方法后用结果做了一些事情。将这些东西放在单独的方法中并从onRequestComplete方法调用它;

var Enabled = false;
function GateWay_Enabled(GateWay_Name) {
    PageMethods.GateWay_Enabled(GateWay_Name, onRequestComplete, onError);
}

function onRequestComplete(result) {
    alert(result); // you will get results here; 
    Enabled = result;
    //do something with value 
}
function onError(result) {
    alert('Error');
}

GateWay_Enabled('GateWay_Name');  // you can't get direct output from this method,  
// have to get results from success callback method or onError callback method 

答案 1 :(得分:1)

调用PageMethods是异步的:在调用函数return Enabled之前执行行onRequestComplete

尝试使用MyVariableonRequestComplete函数中的result代码放入GateWays

在你的Edit2和评论之后,我建议你:

  1. 重构您的PageMethod以返回给定输入ID数组的整个onRequestComplete数组,以避免进行7次AJAX调用。
  2. 当用户点击链接时调用所有这些AJAX,然后将后续代码放在{{1}}方法中。
  3. 或者,如果这些数据在用户点击之间没有变化,我建议您在服务器端获取它。

    没有简单的方法可以确保用户点击代码等待所有七个通话完成。

答案 2 :(得分:0)

您是否在ScriptManager中添加了EnablePageMethods =“true”?

答案 3 :(得分:0)

您在执行MyVariable之前检查onRequestComplete的值