我每次尝试这个时都会得到404。我在代码中找不到错误。我有其他webmethod删除,它的作品。我正在使用带有连接字符串.NET 4.5的WebForm,ADO.NET。我该如何调用WebMethod来返回json和ajax?
[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);
}
这是Ajax调用:
$(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");
}
});
});
});
编辑: 我已经试过这一点,但它亘古不变的工作,我又得到404:
[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;
}
构建您的aspx页面以确保您没有任何错误。 – Pradeep
删除数据属性并参见 –
我在构建项目时没有收到编译错误。将DataTable转换为Json的方法需要一个DataTable并返回一个String – silver1991