【问题标题】:Binding Lable from webmethod using ajax使用ajax从webmethod绑定标签
【发布时间】:2015-06-03 07:53:42
【问题描述】:

嗨,伙计们,我正在尝试从 webmethod 读取数据并将值传递给我在 aspx 页面中的标签。为此,我使用了 Ajax 和 webmethod。我的问题是当我无法将成功的数据绑定到我的标签控件时。

我的 .asmx 页面。

  public static string str;
  [WebMethod]
    public string GetEmployeeDetail(string name)
    {
        str = name;
        Get(str);
        string daresult;
        daresult = Get(str);
        return daresult;
    }

   [WebMethod]
    public string Get(string str)
    {
        List<string> rst = new List<string>();
        using (SqlConnection con = new SqlConnection("..."))
        {
            using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
            {
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while(dr.Read())
                {
                    rst.Add(string.Format("{0}", dr["practice_short_name"]));

                }
                System.Web.Script.Serialization.JavaScriptSerializer jSearializer =  new System.Web.Script.Serialization.JavaScriptSerializer();
                return jSearializer.Serialize(rst);
            }
        }
    }

这是我在 aspx 页面中的 ajax 调用函数。

 function fun() {
         var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");

         $(ddlpsn).change(function () {
             var s = $(this).val();
             $.ajax({
                 type: 'POST',
                 url: 'AutoCompleteService.asmx/GetEmployeeDetail',
                 data: '{name: "' + s + '" }',
                 dataType: 'json',
                 contentType: 'application/json; charset=utf-8',
                 success: function (data) {
               //i think i need to do some changes in here but not getting what to do.
                     $('#lblpriority').text(data.val);
                 },
                 error: function (error) {
                     console.log(error);
                 }
             });
         });
     };

【问题讨论】:

    标签: asp.net ajax webmethod


    【解决方案1】:

    您需要将data.val 更改为data.d。如果您没有为返回的数据明确定义自己的属性,则从WebMethod 返回的数据包含在d 属性中。

    $('#lblpriority').text(data.d);
    

    您需要将WebMethod static 设置为ajax 调用。

    【讨论】:

    • 我试了一下,但没有运气..仍然没有改变任何东西
    • 显示标签代码。如果您的标签是 asp 标签,还要添加 ClientIDMode="static"
    • 你可以看到浏览器控制台,如果你的ajax调用是否成功执行,也可以看到它是否有数据。
    • 感谢您的帮助。现在它正在工作。 $("#").text(data.d);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多