WebForm路由踩坑 ajax请求多次

2022-11-17,,,

WebForm路由踩坑

再次接触Asp.Net WebForm已是4年后的今天,源起新入职的公司,一个老的项目。

Web接触的少,那就多动手写写。

WebForm1.aspx

<body>
<div>
<input type="text" id="text" />
<button type="button" id="clickBtn">ClickMe</button>
</div>
<div id="txt"></div> <script>
$(document).ready(function () { $("#clickBtn").click(function () { var userName = $("#text").val(); $.ajax(
{
type: "post",
url: "/Test/WebForm1.aspx",
dataType: "json",
data: { 'userName': userName }
}
).done(function (data) {
$("#txt").html(data);
});
}); });
</script>

WebForm1.aspx.cs

 public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<string>() { "Hello", "World" }; var userName = HttpContext.Current.Request.Form["userName"]; if (userName != null)
{
list.Add(userName); var data = JsonConvert.SerializeObject(list); HttpContext.Current.Response.ContentType = "json";
HttpContext.Current.Response.Write(data);
HttpContext.Current.Response.End();
}
}
}

运行,发现点击按钮后,并没有实现我们要的效果,并且发出了两次请求

一次Post,一次Get,什么鬼?就这鸟问题,困扰了一上午,还是细细琢磨,不经意间试了一下这个

            $.ajax(
{
type: "post",
url: "/Test/WebForm1",
dataType: "json",
data: { 'userName': userName }
}
).done(function (data) {
$("#txt").html(data);
});

居然就可以了!

那应该是asp.net WebForm觉得.aspx不友好,于是就去掉了,那么帮我们去掉这个过程就是一次重定向过程,怪不得会有一次Get请求。那该是路由设置的问题,于是细细一看。

果然如此,红框中的是默认的配置,实用默认的配置就是永远都要重定向,就算你输入了WebForm1.aspx它都给你重定向成WebForm1。果断设置成Off,问题解决了。

WebForm路由踩坑 ajax请求多次的相关教程结束。

《WebForm路由踩坑 ajax请求多次.doc》

下载本文的Word格式文档,以方便收藏与打印。