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);
        }
    }
}

 

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