使用ASP.NET Webforms的Ajax帖子

Muh*_*sir 2 c# asp.net ajax jquery

我想用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()
Run Code Online (Sandbox Code Playgroud)

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

  [WebMethod]
        public static string update(string userdata)
        {
            return "Posted";
        }
Run Code Online (Sandbox Code Playgroud)

错误:

POST http://localhost:33762/Default.aspx/update   401 Unauthorized 52ms
Run Code Online (Sandbox Code Playgroud)

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

Olu*_*emi 7

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

其次,您的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()
Run Code Online (Sandbox Code Playgroud)