2

我试图将数据发布回位于 Default.aspx 中的 webmethod

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"/>

4

1 回答 1

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;
      }
 }
于 2013-04-12T14:29:34.110 回答