【问题标题】:Using Ajax in a .net project to call a .aspx.cs function NOT WORKING在 .net 项目中使用 Ajax 调用 .aspx.cs 函数不起作用
【发布时间】:2012-07-09 22:01:44
【问题描述】:

我在 .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。

【问题讨论】:

  • 我认为你不能那样做。您的服务器端应该是静态的作为页面方法,并且作为静态方法,您将无法访问标签,因为它是该页面 instance 的成员
  • 问题的质量与(用户名的位数 + 1)*(SO 点数/注册后的月数)成正比。不用说,这个问题的评价不高。

标签: asp.net jquery asp.net-ajax


【解决方案1】:

试着让你的函数静态化。

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

【讨论】:

  • 抱歉,如何从静态方法中访问控件?
  • 你没有,我忽略了那部分并评论了它。
【解决方案2】:

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

以下是有效 JSON 的外观:

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

你的 PageMethod 也需要是静态的:

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

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

【讨论】:

  • 您看到在 FireBug 中发送的请求了吗?服务器对此请求有何响应?
  • 这不起作用,因为服务器端方法是实例方法。 PageMethods 必须是静态的。检查 Henlet Escaño 的答案
【解决方案3】:
 $.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 ";
 }

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 2023-03-27
    • 2012-04-12
    • 1970-01-01
    • 2019-02-25
    • 2014-08-29
    • 2021-02-01
    • 2021-12-29
    • 2014-01-24
    相关资源
    最近更新 更多