【问题标题】:Ajax post with ASP.NET Webforms使用 ASP.NET Webforms 的 Ajax 发布
【发布时间】:2016-08-27 19:24:20
【问题描述】:

我想通过 ajax 调用将数据发布到服务器,但出现错误。

  var userdata = {};
    userdata["Name"] = "Saran";
    var DTO = { 'userdata': userdata };
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/update",
        data: JSON.stringify(DTO),
        datatype: "json",
        success: function (result) {
            //do something
            alert("SUCCESS = " + result);
            console.log(result);
        },

        error: function (xmlhttprequest, textstatus, errorthrown) {
            alert(" conection to the server failed ");
            console.log("error: " + errorthrown);
        }
    });//end of $.ajax()

我在 Default.aspx.cs 中创建了一个函数,并尝试通过上述调用访问该函数。

  [WebMethod]
        public static string update(string userdata)
        {
            return "Posted";
        }

错误:

POST http://localhost:33762/Default.aspx/update   401 Unauthorized 52ms

消息“身份验证失败。” StackTrace null ExceptionType
"System.InvalidOperationException"

【问题讨论】:

    标签: c# jquery asp.net ajax


    【解决方案1】:

    首先,您必须在 App_Start/RouteConfig.cs 中设置/更新为 settings.AutoRedirectMode = RedirectMode.Off;

    其次,您的 ajax 负载结构不正确,无法正确调用 update 方法。请参阅下面的更新:

    var DTO = { 'userdata': 'Saran' };
    $.ajax({
             type: "POST",
             contentType: "application/json; charset=utf-8",
             url: "Default.aspx/update",
             data: JSON.stringify(DTO),
             datatype: "json",
             success: function (result) {
               //do something
               alert("SUCCESS = " + result.d);
                   console.log(result);
              },
             error: function (xmlhttprequest, textstatus, errorthrown) {
                 alert(" conection to the server failed ");
                 console.log("error: " + errorthrown);
             }
          });//end of $.ajax()
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多