caiobsouza
8/19/2015 - 6:19 PM

Recuperando JSON de um Web Service ASP.NET (.asmx) com jQuery.

Recuperando JSON de um Web Service ASP.NET (.asmx) com jQuery.

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class AdventureWeb : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetSalesPerson()
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            DataTable dataTable = new DataTable();

            using (SqlConnection sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["AdventureDB"].ToString()))
            {
                using (SqlDataAdapter sqlDataAdpt = new SqlDataAdapter("SELECT * FROM Sales.SalesPerson", sqlConnection))
                {
                    try
                    {
                        try
                        {
                            sqlConnection.Open();
                        }
                        catch (Exception ex)
                        {
                            return "Sql Connection Failed! " + ex.Message + " " + sqlConnection.ConnectionString; 
                        }
                                                
                        sqlDataAdpt.Fill(dataTable);

                        List<Dictionary<string, object>> dictionaryList = new List<Dictionary<string, object>>();
                        Dictionary<string, object> dictionaryRow;

                        foreach (DataRow row in dataTable.Rows)
                        {
                            dictionaryRow = new Dictionary<string, object>();

                            foreach (DataColumn col in dataTable.Columns)
                            {
                                dictionaryRow.Add(col.ColumnName, row[col]);
                            }
                            dictionaryList.Add(dictionaryRow);
                        }
                        return serializer.Serialize(dictionaryList);
                    }
                    catch (Exception ex)
                    {
                        return "DataSet error! " + ex.Message + " " + ex.StackTrace;
                    }
                    finally
                    {
                        if (sqlConnection.State == ConnectionState.Open)
                        {
                            sqlConnection.Close();
                        }
                    }
                }
            }

        }
    }
$.ajaxSetup({ cache: false});
$.ajax({
  type: "POST",
  //Url do WebService + WebMethod
  url: "/AdventureWeb.asmx/GetSalesPerson",
  contentType: 'application/json; charset=utf-8',
  data: '{}',
  dataType: 'json',
  success: function(response){
    var items = $.parseJSON(response.d);
    $.each(items, function(index, item){
      $('#lista').append("<li>" + item.Propriedade + "</li>");
    });
  },
  error: function(){
    //error
  }
});