使用“webmethod”调用c#方法返回“undefined"

Calling C# method using "WebMethod" returns "undefined"

本文关键字:返回 undefined quot 方法 webmethod 调用 使用      更新时间:2023-09-26

首先,我知道有很多类似的问题,但是没有对我的特殊情况有帮助(很可能我只是需要澄清,我不想打开一个旧的线程)。

我正在创建一个应用程序,我需要调用jQuery函数内的c#方法。我需要这样做的原因是,我需要使用两个特定的参数对数据库执行查询。

Javascript:

$(".button").click(function(){
    var dataId = $(this).attr("data-Id");
    var s = PageMethods.returnStr(dataId, onSuccess, onError);
    function onSuccess(result){
        alert(s);
    }
    function onError(result){
        alert("error");
    }
});
c#:

[WebMethod]
public static string returnStr(string Id)
{       
    // ... blah blah make query, return string s
    return s;
}

返回的字符串未定义。如果我使用alert(result),我只会得到页面的语法。


我也试过引用c#变量使用:

c#

public static string s;
JavaScript:

alert('<%=s%>');

,这可以工作,但是当我调用WebMethod时,我不能修改s。


我尝试过的最后一件事是ajax,但即使我对SO找到的答案进行建模,我也无法让它像我希望的那样工作-它返回"[object object]":

AJAX:

$.ajax({
    type: "POST",
    url: "default.aspx/returnStr",
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    error: function(result){
        alert("request failed" + result)
    },
    success: function(result){
        alert(result);
    }
});
任何建议都是非常感谢的!!

你不能做你提议的事。Javascript在web浏览器中运行。c#在服务器上运行。你不能在浏览器中运行c#代码。

使用alert('<%=s%>');可以工作,因为在发送到客户端之前,它在服务器上进行了评估。

你有两个选择:

    创建一个纯javascript函数来完成你所需要的。
  1. 从ASP控件中使用普通的web窗体事件处理程序(即按钮的OnClick方法)。
  2. 向服务器发起一个AJAX调用来做你需要做的事情。

我看到你尝试了#3,但是你没有做对。URL为"default"。aspx/returnStr"没有任何意义。它不会自动运行default.aspx.cs中的returnStr方法。

你最好使用#2。这是最简单的。

更新:另一个选择是使用asp按钮,如#2,然后在OnClick方法中,使用ClientScript。RegisterStartupScript,它将在回发完成后将Javascript注入页面。在你注入的javascript中,你可以运行下面的代码来打开弹出窗口