我试着发布数据传回位于Default.aspx的一个WebMethod
Im trying to post data back to a webmethod located in Default.aspx
jQuery的code:
jquery code:
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();
}
});
Web方法:
Web Method:
[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的客户端。它实际上并不发布到服务器。有一个<形式GT;
与 =服务器
页面元素。我已经添加了< ASP:的ScriptManager的EnablePageMethods =真=服务器/>
The issue is that the Ajax call always returns an error 500 client side. It does not actually post to the server. there is a <form>
element with runat="server"
in the page. I've added <asp:ScriptManager EnablePageMethods="True" runat="server"/>
您需要ScriptMethod到您的Web方法,因为你需要发送响应为JSON。
You need to ScriptMethod to your web method because you needs to send the response as 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;
}
}