我试图将数据发布回位于Default.aspx
的网络方法jquery代码:
data = "{'saveData':'testtestest'}"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Default.aspx/SavePins",
data: data,
dataType: "json",
success: function (response) {
if (response.d) {
// var obj = JSON.parse(response.d);
}
},
error: function (xhr, ajaxOptions, thrownError) {
$('#modalContentBox').html('Whoops! There was an error saving!').removeAttr('class').attr('class', 'alert alert-error');
$('#myModal').modal();
}
});
网络方法:
[WebMethod]
public bool SavePins(string saveData)
{
try
{
File.WriteAllText(string.Format("{0}{1}.shane", file_location, "pinsData"), saveData);
return true;
}
catch (Exception)
{
return false;
}
}
问题是Ajax调用总是返回错误500客户端。它实际上并没有发布到服务器。页面中有一个<form>
元素runat="server"
。我添加了<asp:ScriptManager EnablePageMethods="True" runat="server"/>
答案 0 :(得分:6)
您需要将ScriptMethod添加到Web方法,因为您需要将响应发送为json。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool SavePins(string saveData)
{
try
{
File.WriteAllText(string.Format("{0}{1}.shane", file_location, "pinsData"), saveData);
return true;
}
catch (Exception)
{
return false;
}
}