使用Request物件實現get/post表單傳值
阿新 • • 發佈:2019-02-12
針對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="提交" onclick="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);
}
}
執行結果:
為空時的執行結果: