我每次嘗試這個時都會得到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