页面跳转并传递参数

Response对象的Redirect方法可以实现页面重定向的功能,并且在重定向到新的URL时可以传递参数。

例如:将页面重定向到welcome.aspx页的代码如下:

Response. Redirect ("~/welcome.aspx");

在页面重定向URL时传递参数,使用“?”分隔页面的链接地址和参数,多个参数时,参数与参数之间使用“&”分隔。

例如:将页面重定向到welcome.aspx页时并传递参数的代码如下:

Response.Redirect("~/welcome.aspx?parameter=one ");

Response.Redirect("~/welcome.aspx?parameter1=one&parameter2=other");

下面示例主要通过Response对象的Redirect方法实现页面跳转并传递参数。执行程序,在TextBox文本中输入姓名并选择性别,单击【确定】按钮,跳转到“welcome.aspx”页,示例运行结果如图12所示。

 

1  页面跳转传递参数

 

2  重定向的新页

程序实现的主要步骤:

1)新建一个网站,默认主页为Default.aspx,在Default.aspx页面上添加一1TextBox控件、一个Button控件、两个RadioButton控件,它们的属性设置如表1所示。

1                         Default.aspx页面中控件属性设置及其用途

控件类型

控件名称

主要属性设置

用途

标准/TextBox控件

txtName

 

输入姓名

标准/Button控件

btnOK

Text属性设置为“确定”

执行页面跳转并传递参数的功能

标准/RadioButton控件

rbtnSex1

Text属性设置为“男”

显示“”文本

Checked属性设置为True

显示为选中状态

rbtnSex2

Text属性设置为“女”

显示“”文本

在【确定】按钮的btnOK_Click事件中实现跳转到页面welcome.aspx页面并传递参数NameSex。代码如下:

protected void btnOK_Click(object sender, EventArgs e)

{

    string name=this.txtName.Text;

    string sex="先生";

    if(rbtnSex2 .Checked)

        sex="女士";

    Response.Redirect("~/welcome.aspx?Name="+name+"&Sex="+sex);

}

2)在该网站中,添加一个新页,将其命名为welcome.aspx。在页面welcome.aspx的初始化事件中获取Response对象传递过来的参数,并将其输出在页面上。代码如下:

protected void Page_Load(object sender, EventArgs e)

{

    string name = Request.Params["Name"];

    string sex = Request.Params["Sex"];

    Response.Write("欢迎"+name+sex+"!");

}