私はこれを試すたびに404を取得します。私のコードでエラーを見つけることができません。私は削除する他のwebmethodを持っており、それは動作します。私はWebForm、ADO.NETと接続文字列、.NET 4.5を使用しています。WebMethodをajaxでjsonを返すように呼び出すにはどうすればよいですか?
[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呼び出しです:私は再び404を取得し、私はこれを試してみましたが、それは仕事をdoesnot :
$(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");
}
});
});
});
編集
[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を必要とし、文字列を返します。 – silver1991