针对HTML控件
使用Post方式提交表单到WebForm4中
在主页WebForm3中
<!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>
<style type="text/css">
.auto-style1 {
width: 45%;
}
</style>
</head>
<body>
<form id="form1" runat="server" method="post" action="WebForm4.aspx">
<div>
<table class="auto-style1">
<tr>
<td>用户名</td>
<td>
<input id="Text1" type="text" name="a"/></td>
</tr>
<tr>
<td>密码</td>
<td>
<input id="Password1" type="password" name="b"/></td>
</tr>
<tr>
<td>
<input id="Submit1" type="submit" value="提交" /></td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
</html>
WebForm4中显示传递的表单信息:
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name = Request.Form["a"];
string password = Request.Form["b"];//对于HTML控件,只能用控件的name
Response.Write("<h1>您的信息如下</h1>");
Response.Write("<p>用户名为:" + name);
Response.Write("<p>密码为:" + password);
}
}
运行结果:
针对Web服务器控件:
①采用post方式时,Request.Form[" "]必须是控件的ID,不能使用name,实现方法同上
②采用get方式,采用传递URL的形式
WebForm3.aspx中
<!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>
<style type="text/css">
.auto-style1 {
width: 45%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td>用户名</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>密码</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="提交" οnclick="Button1_Click"/>
</td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
</html>
在WebForm3.aspx.cs中给button添加触发函数,使之给WebForm4发送URL,注意表单中不能有action="WebForm4",因为Button的默认type是submit,点击button后同样会触发表单的提交和WebForm4的加载,使得第2次加载的WebForm4会覆盖之前因为redirect传递URL的第1次加载,导致第1次的传值效果被覆盖。
WebForm3.aspx.cs中:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.Trim() != "" && TextBox2.Text.Trim() != "")//去空格后是否为空判断
Response.Redirect("WebForm4.aspx?name=" + TextBox1.Text + "&pwd=" + TextBox2.Text);
else
ClientScript.RegisterStartupScript(this.GetType(),"系统提示","<script>alert('不能为空')</script>");
}
WebForm4.aspx.cs中
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name = Request.QueryString["name"];//获取URL里面name参数的值
string password = Request.QueryString["pwd"];//获取URL里面pwd参数的值
Response.Write("<h1>您的信息如下</h1>");
Response.Write("<p>用户名为:" + name);
Response.Write("<p>密码为:" + password);
}
}
运行结果:
为空时的运行结果: