Ajax POST数据未发送到ASP.NET中的Page_Load方法

Ajax POST Data not being sent to the Page_Load method in ASP.NET

本文关键字:中的 NET Page 方法 Load ASP 数据 POST Ajax      更新时间:2023-09-26

我基本上是在尝试将一些测试值从javascript函数发送到ASP.NET Web Forms页面中的Page_Load方法。

然而,在调试时,我注意到Request数据为null,并且没有通过条件

代码:

test.aspx

<form id="form1" runat="server">
        <div>
            <input type="button" onclick="senddata()" />
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            function senddata() {
                var testdata = "checkcheck";
                $.ajax({
                    type: 'POST',
                    url: '/test.aspx',
                    data: { "data": testdata},
                    success: function (msg) {
                        console.log(msg);
                    }
                });
            }
        </script>
</form>

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    //doesn't go beyond this when I click the button
    if (!string.IsNullOrEmpty(Request.Form["data"]))
    {
        string resp = "working";
        Response.Write(resp );
        Response.End();
        return;
    }
}

知道为什么没有从代码后面接收到数据吗?这是一个非常简单的例子,我想知道为什么。

"Request.Form["data"]"最初为null,因为"data"中没有值。但当您在ajax方法上调用"test.aspx"时,它会再次调用pageload事件并将Request.Form["data"]重置为null。

相反,您应该创建一个web方法,并在senddata((函数中调用该方法。

感谢您的回复!我设法通过做以下更改来修复它:

内部~/App_Start/RouteConfig.cs

我更改了:settings.AutoRedirectMode = RedirectMode.Permanent;

settings.AutoRedirectMode = RedirectMode.Off;

这解决了问题。我不知道这个配置是怎么进来的。它是在我创建项目时添加到RouteConfig的。希望这能帮助到别人。