Detailed explanation of several ways to transfer values ​​between ASP.NET pages

高洛峰
Release: 2017-01-21 15:42:51
Original
1385 people have browsed it

Opening Overview

For any beginner, transferring values ​​​​between pages is the only way to go, but it is also a difficulty for them. In fact, it may not be difficult for most experts.

Looking back at the nearly 300 people interviewed in 2016, there were interns, fresh graduates, people with 1-3 years of experience, people with 3-5 years of experience, and people with 5-10 years of experience. For I almost asked all the interviewees the same question: "Please tell me about the several forms and methods of value transfer between pages that you know, and explain their principles and processes." Regarding this question, from everyone's Judging from the answers, the results are not very ideal. In terms of types, most people answer about 5 types, and a very few people can answer 8 types. There are no more than 8 types. But in terms of depth, few people can give a thorough analysis. The principles and processes of each method (of course, to thoroughly analyze these principles and processes, you need to study the underlying things, such as page life cycle and page principles, reflection, how IIS parses requests, etc., CLR, GC, decompilation, etc. ).

To give a rough summary, the methods of transferring values ​​between ASP.NET pages can be roughly divided into the following types: Request.QueryString["name"],Request.Form("name"),Session,Cookie,Cache , Application, Server.Transfer, Database, Item properties of HttpContext, Files, DataBase, etc.

Detailed explanation of each method

1. Request.QueryString

Core code:

protected void getQueryString_Click(object sender, EventArgs e)
 {
   string QueStr = Request.QueryString["name"];
   Response.Write(QueStr);
 }
Copy after login

Summary:

1.Request.QueryString : Get the http query string variable collection. There are two overloads, namely Request.QueryString[string name] and Request.QueryString[int index];

2. Request.QueryString mainly obtains the parameters after "?" in the url, such as url:a .aspx?name="queryString", then the value of Request.QueryString["name"] is "queryString".

2. Request.Form

Core code:

protected void getQueryString_Click(object sender, EventArgs e)
 {
   string strQueForm = Request.Form["TextBox1"];
   Response.Write(strQueForm);
 }
Copy after login

Summary:

1. Request.Form obtains the form variable collection. There are two overloads, namely Request.Form[string name] and Requst.Form[int index].

2. Get the parameter value of the specified name in the form.

3. Session

1. Basic operations of Session

a. Create Session

//创建Session
    public void createSession(string[] arrStr)
    {
      //创建数组
      string[] str=new string[arrStr.Length];
      for (int i = 0; i < arrStr.Length; i++)
      {
        str[i] = i.ToString();
        Session[str[i]] = arrStr[i];
      }
    }
Copy after login

b. Get the value of Session

string getSessionValue=Session["name"].ToString();
Copy after login

c. Traverse the Session

//遍历Session
    public void getSession()
    {
      IEnumerator sessionEnum = Session.Keys.GetEnumerator();
      while (sessionEnum.MoveNext())
      {
        Response.Write(Session[sessionEnum.Current.ToString()].ToString()+";");
      }
    }
Copy after login

d. Clear the Session without ending the session

//清空Session,但不结束会话
    public void clearSession()
    {
      Session.Clear();
    }
Copy after login


e. End the Session

//结束Session会话
    public void abandonSession()
    {
      Session.Abandon();
    }
Copy after login


2. Session data storage format and location

<system.web>
 <sessionState mode="Off|InProc|StateServer|SQLServer" cookieless="true|false" timeout="number of minutes"
 stateConnectionString="tcpip=server:port" sqlConnectionString="sql connection string" stateNetworkTimeout="number of seconds"/>
</system.web>
Copy after login


Note:

mode: Indicates setting the session data storage format and location;

a, Off: Disable Session;

b, Inproc: In Process abbreviation, indicating that the Session is stored in the IIS process, but note that although this method has high performance, restarting IIS will cause Lose Session information; (default value)

c, SateServer: Store the Session in the ASP.NET state service process (retain the session state when restarting the web application and make the session state available for use in the network) Multiple Web servers);

d. Store Session in SQL Server

cookieless: Set the client storage session form and location

a.true: Use cookieless mode , then the client's Session information is no longer stored using Cookie, but is stored through the URL;

b, false: Use kookie mode, default value.

timeout sets the number of minutes after which the server automatically gives up the session information. The default is 20 minutes;

stateConnectionString sets the server name and port number used when storing Session information in the state service, for example: "tcpip=127.0.0.1:42424". This attribute is required when the value of mode is StateServer. (Default port 42424);

sqlConnectionString Sets the connection string when connecting to SQL Server. For example "data source=localhost;Integrated Security=SSPI;Initial Catalog=joye". When the value of mode is SQLServer, this attribute is required;

stateNetworkTimeout sets when using StateServer mode to store Session state, after how many seconds of idle time, disconnect the TCP/TCP/ IP connected. The default value is 10 seconds;

3. Session principle

Why is Session introduced? As we all know, because http is a stateless protocol, Session makes up for this shortcoming. Of course, the role of Session is far more than these, so I won’t discuss it here.

Session in ASP.NET represents the session between the client (Goggle, Firefox, IE, etc.) and the server. It is used to store specific session information. To be precise, it is used to store specific user information. When the client sends a request to the server, such as a logged-in user ID, and the server receives the request, the server-side Session generates a SessionID related to the logged-in user, and returns the SessioID to the client (Goggle, Firefox, IE, etc.). At the beginning of a new session, the server stores the SessionID as a cookie in the user's browser.

Summary:

1. Definition: System.Web.SessionState.HttpSessionState Page.Session //Get the current Session object provided by ASP.NET.

2. Features:

a. Session means "session" in Chinese. In ASP.NET, it represents the session between the client and the server. It is one of the commonly used sessions in the web.

b. Session is stored in server-side memory.

c. Session can store any type of data, including custom objects.

d、Session与Session间是相互独立的,互不干扰。

e、Session与Cookie配对使用,Session在服务器端产生SessionID,并将该SessionID返回给客户端(IE,FireFox,Google等),客户端Cookie来存储该SessionID,整过会话过程中,只要保存SessionID的Cookie不丢失,则Session的信息就不会丢失。

f、Session保存的数据可以跨页访问,即跨页面是全局的。

g、Session不能跨进程访问,只能由该会话用户访问。

h、可以在不结束会话的条件下,清除Session信息,即调用Session.Clear();

i、当会话结束,过期,服务器就会清除Session对象。

j、Session常用于保存登录用户的ID.

四、Application

核心代码:

(1)a.aspx

private void Button1_Click(object sender, System.EventArgs e)
{
  Application["name"] = Label1.Text;
}
Copy after login


(2)b.aspx

private void Page_Load(object sender, EventArgs e)
{
  string name;
  Application.Lock();
  name = Application["name"].ToString();
  Application.UnLock();
}
Copy after login


总结:

1、Application对象的作用范围是整个全局,也就是说对所有用户都有效。它在整个应用程序生命周期中都是有效的,类似于使用全局变量一样,所以可以在不同页面中对它进行存取。它和Session变量的区别在于,前者是所有的用户共用的全局变量,后者是各个用户独有的全局变量。可能有人会问,既然所有用户都可以使用application变量,那他可以用在什么场合呢?这里举个例子:网站访问数。多个请求访问时都可以对它进行操作。

2、优点:使用简单,消耗较少的服务器资源;不仅能传递简单数据,还能传递对象;数据量大小是不限制的。

3、缺点:作为全局变量容易被误操作。所以单个用户使用的变量一般不能用application。

4、在源页面的代码中创建你需要传递的名称和值构造Application变量:Application["name"]="Value(Or Object)";在目的页面的代码使用Application变量取出传递的值。Result = Application["name"]。

5、常用lock和unlock方法用来锁定和解锁,为了防止并发修改。

五、Cache

核心代码:

//Class1
 
 Cache["id"] = TextBox1.Text;
 Response.Redirect("~/WebForm1.aspx");
 
//Class2
 
if (Cache["id"]!=null)
 {
   Label1.Text = Cache["id"].ToString();
 }
 
//移除缓存
Cache.Remove("id");
 
//如果 Cache["id"]为空,则传值失败。可使用如下方法实
//限期为10分钟
 Cache.Insert("id",TextBox1.Text,null,Cache.NoAbsoluteExpiration,new TimeSpan(0,10,0));
Copy after login


总结:

1、应用程序中的缓存机制用于将需要大量服务器资源来创建的对象存储在内存中,以此大大改进应用程序的性能。这个机制同样可以用来传值。

2、与其他方法不同的是,该方法需要设置缓存项优先级和缓存时间。因为当系统内存缺乏时,缓存机制会自动移除很少使用或优先级较低的项,从而造成传值失败。

3、该方法的优点是传递数据的大小和数量无限制,速度快。缺点是缓存机制的操作相对比较复杂。

六、Cookie

核心代码:

//Class1
 
HttpCookie httpCookie = new HttpCookie("testCookie","Page transfers by Cookie");
Response.Redirect("~/Class2.aspx");
//Class2
 
Label1.Text = Request.Cookies["testCookie"].Value;
Copy after login


总结:

1、Cookie用于在用户浏览器上存储小块的信息,保存用户的相关信息,比如用户访问某网站时用户的ID,用户的偏好等,用户下次访问就可以通过检索获得以前的信息。所以Cookie也可以在页面间传递值。

2、Cookie通过HTTP头在浏览器和服务器之间来回传递的。Cookie只能包含字符串的值,如果想在Cookie存储整数值,那么需要先转换为字符串的形式。

3、与Session一样,其是什对每一个用户而言的,但是有个本质的区别,即Cookie是存放在客户端的,而session是存放在服务器端的。而且Cookie的使用要配合ASP.NET内置对象Request来使用。

4、使用简单,是保持用户状态的一种非常常用的方法。比如在购物网站中用户跨多个页面表单时可以用它来保持用户状态。

5、常常被人认为用来收集用户隐私而遭到批评。

6、安全性不高,容易伪造。

七、Context.Items["id"]

核心代码:

//Class1
 
 Context.Items["id"]=TextBox1.Text;
 Server.Transfer("~/Class2.aspx");
 
//Class2
 Label1.Text=Context.Items["id"].ToString();
 Context.Items.Remove("id"); //移除项
Copy after login


1、Context 对象包含与当前页面相关的信息,提供对整个上下文的访问,包括请求、响应、以及上文中的Session 和Application 等信息。

2、可以使用此对象在网页之间共享信息,从而实现页面间的传值。

3、与使用 Form 的方法类似,该方法也能保持大量的数据,缺点也相同,但使用方法相对比较简单。

八、ViewState

核心代码:

//Class1
ViewState["id"]=TextBox1.Text; //数据保存
Label1.Text=ViewState["id"].ToString(); //数据取出
ViewState.Remove("id"); //数据移除
Copy after login


总结:

1、ViewState 是ASP.NET 用来在同一页面的多个请求之间保存和还原服务器控件视图状态的一种机制。与传统的“同一页面”不同,ASP.NET 中“同一页面”的每一个请求都会导致服务器重新生成该页面,但是新生成的页面并不包含原来页面的数据。(页面无状态性)

2、ViewState 的任务就是保存原来页面中服务器控件视图状态的数据供新页面使用。从这个意义上讲,ViewState 也可以看作是一种在页面间传递数据的工具。

3、ViewState 的工作原理是:作为一个隐藏的窗体字段在客户端和服务器之间传递,可见,滥用ViewState 会加重页面回传的负担,从而降低应用程序的性能。

此外,ViewState 也能被控件、页面和应用程序禁用。

九、web.config和machine.config

核心代码:

//Class1
using System.Web.Configuration;
WebConfigurationManager.AppSettings.Set("userName",TextBox1.Text);
Response.Redirect("~/Class2.aspx");
//Class2
using System.Web.Configuration;
Label1.Text = WebConfigurationManager.AppSettings["userName"];
Copy after login


总结:

1、每个Web运用程序继承web.config文件和machine.config文件的设置。

2、web.config和machine.config这两种文件保存数据一般都很小,多为明文,特别适合保存一些字符串常量,如数据库连接信息。此外,web.config文件是可以扩展的,因此,也可以用来传递变量。由于这两种文件会被自动缓存,所以不存在因磁盘IO产生的性能瓶颈等问题。要注意的是文件中某些设置会导致文件被修改后Web运用程序的重启。

3、web.config:你可以向单个Web运用程序运用设置。例如,你可能会希望设置特定的验证方法、调试的类型、默认语言或自定义的错误页面。但如果你要使用这些设置,必须把web.config文件放到web运用程序的根虚拟目录下。要想在Web运用程序中进一步配置自己的子目录,需要 在这些文件夹中放置附加的web.config。(关于ASP.NET web.config文件详细介绍,可参考我另外一篇博客:ASP.NET web.config)

4、machine.config:从c:\Windows\Microsoft.NET\Framework\Framework\[Version]\Config目录中的一个叫macine.config的文件开始 配置。machine.config文件定义支持的配置文件节,配置ASP.NET工作者进程,注册可用于高级特性(如配置文件、成员资格以及基于角色的安全等)提供程序。(关于ASP.NET machine.config文件的详细介绍,我之后会写一篇文章来介绍)

十、Static

核心代码:

//class1
public static string userName;//在class1中定义静态全局变量
userName=txtBoxUserName.Text;
Response.Redirect("~/class2.aspx");
//class2
Label1.Text=Src.id;
Copy after login


总结:

1、这个应该是非常容易理解的,在ASP.NET中,每个页面对应一个具体的类,既然如此,那么页面之间的传递,我们就可以归结为:类与类之间数据的传递。想到这一步,问题应该就迎刃而解了, 因为我们可以利用类之间的公关静态变量来解决这个问题。

2、若合理利用,可以有效地提高数据传递效率,但若滥用,可能会导致用户或页面间数据紊乱,存在一定风险和隐患,应谨慎使用。

提出以下问题:大家可以分析一下,以下代码有什么问题?

//Class1
 
 protected void btnRedirect_Click(object sender, EventArgs e)
    {
        
      string userName = txtBoxUserName.Text;
      Response.Redirect("~/Class2.aspx");
    }
 
//Class2
 
Lable1.Text=userName;
Copy after login


十一、补充常用页面之间跳转

1.最常用的页面跳转(原窗口被替代):Response.Redirect("XXX.aspx");

2.利用url地址打开本地网页或互联网:Respose.Write("");

3.原窗口保留再新打开另一个页面(浏览器可能阻止,需要解除):Response.Write("<script>window.open('XXX.aspx','_blank')</script>");

4.效果同1中的另一种写法:Response.Write("<script>window.location='XXX.aspx'</script>");

5.也是原窗口被替代的 (常用于传递session变量的页面跳转):Server.Transfer("XXX.aspx");

6.原窗口保留,以对话框形式打开新窗口:Response.Write("<script>window.showModelessDialog('XXX.aspx')</script>");

7.对话框形式打开新窗口,原窗口被代替:Response.Write("<script>window.showModelDialog('XXX.aspx')</script>");

8.打开简洁窗口:Respose.Write("");

9.利用vs2008端口:System.Diagnostics.Process.Start(http://localhost:3210/系统管理员.aspx);

注释:比较简单,我这里就不论述了。

总结:

关于页面之间传值,还有很多方法,如文件传值、数据库传值,ViewBag等等,在这里就不一一论述了。若以后有时间,将会在此基础上补充,并逐步完善该篇博文。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多详解ASP.NET 页面之间传值的几种方式相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!