-1

我在 .net 项目中使用 Ajax(不是 MVC.net)。我想从 JScript 函数中调用我的 .aspx.cs 函数。

这是我的 JScript 代码:

    $("a#showQuickSearch").click(function () {
        if ($("#quick_search_controls").is(":hidden")) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SetInfo",
                data: "{showQuickSearch}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
               success: function(response) {
                     alert(response.d);
               }

            });
            $("#quick_search_controls").slideDown("slow");
            $("#search_controls").hide();
            $("#search").hide();
        } else {
            $("#quick_search_controls").hide();
        }

    });

这是我的 .aspx.cs 函数:

   [WebMethod]
    public string SetInfo(string strChangeSession)
    {
        Label1.Text = strChangeSession;
        return "This is a test";
    }

问题是我的 .aspx.cs 函数没有被调用,也没有更新 label.text。

4

3 回答 3

1

尝试使您的功能静态。

[WebMethod]
    public static string SetInfo(string strChangeSession)
    {
        //Label1.Text = strChangeSession; this wont work
        return "This is a test";
    }
于 2012-07-09T22:03:39.080 回答
1

data: "{showQuickSearch}"不是有效的 JSON。

下面是一个有效的 JSON 的样子:

data: JSON.stringify({ strChangeSession: 'showQuickSearch' })

您的 PageMethod 也需要是静态的:

[WebMethod]
public static string SetInfo(string strChangeSession)
{
    return "This is a test";
}

这显然意味着您无法访问任何页面元素,例如标签和内容。在您的成功回调中,您现在可以使用 PageMethod 的结果来更新某些标签或其他内容。

于 2012-07-09T22:04:05.390 回答
0
 $.ajax({
            type: "POST",
            url: "Default.aspx/SetInfo",
            data: "{'strChangeSession':'showQuickSearch'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                 alert(response.d);
           },
          error: function (xhr, status, error) {

                var msg = JSON.parse(xhr.responseText);
                alert(msg.Message);
            }
        });

你的后端代码:

 [WebMethod]
 public static string SetInfo(string strChangeSession)
 {
   return "Response ";
 }
于 2012-07-09T22:29:17.737 回答