使用ajax从web方法绑定Lable

时间:2015-06-03 07:53:42

标签: asp.net ajax webmethod

嗨guyes我正在尝试从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);
                 }
             });
         });
     };

1 个答案:

答案 0 :(得分:0)

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

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

您需要设置WebMethod static才能通过ajax进行调用。