ASP.NET回发数据是通过函数__doPostBack来实现的,该函数在添加了服务端控件,并将AutoPostBack设置为true之后,将自动生成,具体可以参看下面的图。
同时还会生成隐藏控件,其ID为__EVENTTARGET和__EVENTARGUMENT,前一个是用于存放key的,后一个用于存放参数的。
所以在后台通过Request.Form来获取所要的数据,test.aspx.cs代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ExampleTest { public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { String key = Request.Form["__EVENTTARGET"]; if (!String.IsNullOrWhiteSpace(key)) { String value = Request.Form["__EVENTARGUMENT"]; String info = "Key=" + key + " Value=" + value; Response.Write("<script type=\"text/javascript\">alert('" + info + "');</script>"); TextBox1.Text = info; } } } }
注:
对于Button和ImageButton会有不一样,可以参考下面的文章
http://blog.csdn.net/luxuejuncarl/article/details/1479226
http://www.cnblogs.com/hjf1223/archive/2006/07/05/443761.html
效果图:
附前端代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="ExampleTest.test" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript"> function test() { __doPostBack("AA", "111"); } </script> </head> <body> <form id="form1" runat="server"> <div> <input id="btnTest" type="button" onclick="test();" value="test" /> <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true"></asp:TextBox> </div> </form> </body> </html>
ASP.NET之通过JS向服务端(后台)发出请求(__doPostBack is undefined)
时间: 2024-10-28 10:28:15