Search code examples
asp.netajaxwebmethod

Binding Lable from webmethod using ajax


Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.

my .asmx page.

  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);
            }
        }
    }

and here is my ajax call function in aspx page.

 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);
                 }
             });
         });
     };

Solution

  • You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.

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

    You need to make your WebMethod static in order to called by ajax.