使用ASP.NET Webforms的Ajax帖子 [英] Ajax post with ASP.NET Webforms

查看:48
本文介绍了使用ASP.NET Webforms的Ajax帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to post data to server with ajax call but i am getting an error.

  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中创建了一个函数,并试图通过上述调用访问该函数。

I have created a function in Default.aspx.cs and tried to access that function with the above call.

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

错误:


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

消息身份验证失败。 StackTrace null ExceptionType

System.InvalidOperationException

Message "Authentication failed." StackTrace null ExceptionType
"System.InvalidOperationException"


推荐答案

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

其次,您的ajax有效负载结构不正确,无法对 update 方法进行适当的调用。请参阅以下更新:

Secondly, your ajax payload is not structured properly to make the appropriate call to the update method. See updates below:

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()

这篇关于使用ASP.NET Webforms的Ajax帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆