ASP.Net中常用到的几种跳转方式;Response.Redirect()、sever.execute、Response.Write()
1、Response.Redirect(" ");
这种跳转页面方法速度不快,因为它要走2次来回(PostBack),但它可以跳转到任何页面,没有站点页面限制,同时不能跳过登录保护;速度慢是最大缺陷!
Redirect跳转机制:首先是发送一个http请求到客户端,通过需要跳转到新页面,然后客户端再发送跳转请求到服务器端。要注意的是跳转后内部空间保存的所有数据信息将丢失,所以需要用到Session Cookies Application等对象进行页面间的数据传递。
Response.Redirect("/View/Home.aspx",false);
//false:是否关闭当前页面;(“ ”)默认为关闭
带参数跳转
1.使用queryString传值,跳转到指定页面
Response.Redirect("/View/Home.apsx"+"?userName="+userName+"&passWord="+passWord);
获取参数
this.Label1.Text = Request.QueryString["userName"];
this.Label2.Text = Request.QueryString["passWord"];
2.使用Application传值,跳转到指定页面
Application["userName"] = userName;
Application["passWord"] = passWord;
Response.Redirect("/View/Home.aspx");
获取参数
this.Label1.Text = Application["userName"].ToString();
this.Label2.Text = Application["passWord"].ToString();
3.使用Session传值,跳转到指定页面
Session["userName"] = userName;
Session["passWord"] = passWord;
Response.Redirect("/View/Home.aspx");
获取参数
this.Label1.Text = Session["userName"].ToString();
this.Label2.Text = Session["passWord"].ToString();
4.使用Cookie传值,跳转到指定页面(cookie存放中文乱码使用HttpUtility.UrlEncode()编码)
HttpCookie cookieName =new HttpCookie("userName",HttpUtility.UrlEncode(UserName));
HttpCookie cookiePwd = new HttpCookie("passWord",HttpUtility.UrlEncode(PassWord));
Response.Cookies.Add(cookieName);
Response.Cookies.Add(cookiePwd);
Response.Redirect("/View/Home.aspx");
获取参数(提取时需HttpUtility.UrlDecode()解码)
this.Label1.Text = HttpUtility.UrlDecode(Request.Cookies["userName"].Value);
this.Label2.Text = HttpUtility.UrlDecode(Request.Cookies["passWord"].Value);
2、sever.execute
主要是用在页面设计上面,而且它必须是跳转同一站点下的页面;这个方法是需要将一个页面的输出结果插入到另一个aspx页面的时候使用,大部分是在表格中,将某一个页面类似于嵌套的方式存在于另一页面。
例子:
1.创建一个webform页面,“Home.aspx”
2.在“Home.aspx”放置一个button1,在放置两个TextBox1,TextBox2
3.创建过程来返回TextBox1,TextBox2控件的值代码如下:
4.定义一个实体类,并创建一个实体对象集合;
5.给button1添加点击事件,给实体集合添加数据
代码如下↓↓↓
//创建对象过程返回文本框的值
public string Name
{
get
{
return text1.Text;
}
}
public string EMail
{
get
{
return text2.Text;
}
}
//创建一个实体
public class stuModel
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
//创建实体集合对象
public List<stuModel> stu = new List<stuModel>();
protected void btn_Click(object sender, EventArgs e)
{
//给实体集合添加数据
stu = new List<stuModel>(){
new stuModel(){ Name="张三",Age=18,Sex="男"},
new stuModel(){ Name="洁芬",Age=18,Sex="女"}
};
Server.Transfer("/View/studentData.aspx");
}
6.创建一个页面,“studentData.aspx”
然后获取值代码如下↓↓↓
//创建原始窗体的实例
Home home;
//获得实例化的句柄(页面对象)
home = (Home)Context.Handler;
//获取Home.aspx页面文本框输入的值
this.Label1.Text = home.Name;
this.Label2.Text = home.EMail;
//获取Home.aspx页面实体集合的值
List<Home.stuModel> stu = home.stu;
3、server.transfer(这种没尝试)
4、Response.Write("");
写入JavaScript代码实现跳转(传参数也是在跳转url后面拼接)
Response.Write("<script languge='javascript'>parent.location.href='/View/Login.aspx';</script>");