silver1991 silver1991 - 2 months ago 25
jQuery Question

How can I call a WebMethod to return json with ajax?

I get 404 every time I try this. I can't find the error in my code. I have other webmethod to delete and it works. I am using a WebForm , ADO.NET with a connection string, .NET 4.5.

[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ListarTiposLicencia()
{
TipoLicenciaBL objTipoLicencia = new TipoLicenciaBL();
//Return a DataTable from database with a stored procedure
DataTable dt = objTipoLicencia.DevolverListaTipoLicencia(String.Empty, String.Empty);
return DataTableToJSONWithJavaScriptSerializer(dt);
}

public static string DataTableToJSONWithJavaScriptSerializer(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}


This is the ajax call:

$(document).ready(function () {
$("#obtenerLicencias").click(function () {
$.ajax({
type: "POST",
url: "CnfListaTipoLicencias.aspx/ListarTiposLicencia",
data: '{ }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
alert(JSON.parse(data));
},
failure: function (response) {
alert("Error");
},
error: function (error) {
alert("error");
}
});

});
});


Edit:
I have tried this, but it doesnot work, I get 404 again:

[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ListarTiposLicencia()
{
TipoLicenciaBL objTipoLicencia = new TipoLicenciaBL();
DataTable dt = objTipoLicencia.DevolverListaTipoLicencia(String.Empty, String.Empty);
string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
return json;
}

Answer

Try This

DataTable dt = objTipoLicencia.DevolverListaTipoLicencia(String.Empty, String.Empty);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);

But make it sure that the DataTable (dt) populate with some data.

Comments