ASP.NET中Response實現頁面跳轉傳參的簡單方法

Response

Response對象用於將數據從服務器發送回瀏覽器。
它允許將數據作爲請求的結果發送到瀏覽器中,並提供有關響應的信息;還可以用來在頁面中輸入數據、在頁面中跳轉,並傳遞各個頁面的參數。它與HTTP協議的響應消息相對應。假如將用戶請求服務器的過程比喻成客戶到櫃檯買商品的過程,那麼在客戶描述要購買的商品(如功能、大小、顏色等)後,銷售員就會將商品擺在客戶的面前,這就相當於Response對象將數據從服務器發送回瀏覽器。
response 經常用在頁面跳轉及傳參的動作中,通過Response對象的Redirect方法可以實現頁面重定向的功能,並且在重定向到新的URL時可以傳遞參數。

例如 單純的頁面挑戰。從default頁面跳轉到menu頁面。Response.Redirect("~/Menus.aspx);

平時見到的跳轉都是要提交參數到目標頁面。在頁面重定向URL時傳遞參數,使用“?”分隔頁面的鏈接地址和參數,有多個參數時,參數與參數之間使用“&”分隔。例如,從default頁面跳轉到menu頁面時攜帶用戶信息 Response.Redirect("~/Menus.aspx?Name=" + name + "&Sex=" + sex);目標頁面則使用 request接參,例如  lab_welcome.Text = string.Format("歡迎{0}{1}訪問主頁", name, sex);

下面舉例:1創建頁面,並添加提交用戶信息的幾個控件,讓用戶提交姓名和性別,然後傳參到目標頁面:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!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>ASP.NET課程學習</title>
</head>
<body>
<form id="form1" runat="server">
    <label>姓名</label>
    <asp:TextBox runat="server" ID="naembox"></asp:TextBox>
    <br/>
    <label>性別</label>
    <asp:RadioButton runat="server" ID="rdo_man" Checked="True"/>
    <asp:RadioButton runat="server" ID="rdo_wowan"/>
    <br/>
    <asp:Button runat="server" ID="direction" Text="response跳轉" OnClick="direction_OnClick"/>
</form>
</body>
</html>

2 寫提交動作:

  protected void direction_OnClick(object sender, EventArgs e)
        {
            var name = naembox.Text;
            var sex = "";
            if (rdo_man.Checked)
            {
                sex = "先生";
            }
            else
            {
                sex = "女士";
            }
            Response.Redirect("~/Menus.aspx?Name=" + name + "&Sex=" + sex);
            Response.AppendToLog("tiaozhuanl");
        }


3 在目標網頁使用一控件接受並展示參數:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Menus.aspx.cs" Inherits="WebApplication1.Menus" %><!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>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <asp:Label runat="server" ID="lab_welcome"></asp:Label>
    </div>
</form>
</body>
</html>

4 目標網頁接受動作的實現:

using System;
using System.Web.UI;

namespace WebApplication1
{
    public partial class Menus : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var name = Request.Params["Name"];
            var sex = Request.Params["Sex"];
            lab_welcome.Text = string.Format("歡迎{0}{1}訪問主頁", name, sex);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章