Ajax调用总是返回错误500客户端

时间:2013-04-12 14:25:21

标签: javascript jquery asp.net ajax

我试图将数据发布回位于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"/>

1 个答案:

答案 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;
      }
 }