Home Backend Development C#.Net Tutorial Several ways to transfer values ​​between ASP.NET pages

Several ways to transfer values ​​between ASP.NET pages

Mar 05, 2017 pm 12:27 PM
asp.net

Page value passing is a problem that everyone will face in the early stage of learning asp.net. Generally speaking, there are page value passing, storage object value passing, ajax, class, model, form, etc. But generally speaking, the commonly used simpler ones are QueryString, Session, Cookies, Application, and Server.Transfer. During interviews, we often encounter such questions. In fact, we are familiar with several of these methods because they are often used in projects. However, it is estimated that it is often difficult to comprehensively answer the method of page value transfer in ASP.NET.

 1. QueryString

QueryString is a very simple way of passing values. It can display the transmitted value in the address bar of the browser. This method can be used when passing one or more values ​​with low security requirements or simple structure. But for passing arrays or objects, this method cannot be used.

 Advantages of this method: 1. It is simple to use and is very effective for transferring numbers or text values ​​when security requirements are not high.
 Disadvantages of this method: 1. Lack of security because its value is exposed in the browser's URL address.
      2. Objects cannot be passed.

 Usage: 1. Construct the URL address in the code of the source page with the name and value that needs to be passed.
   2. Use Response.Redirect(URL); in the code of the source page to redirect to the above URL address.
   3. Use Request.QueryString["name"]; in the code of the destination page to retrieve the value passed in the URL address.

 Example:(1)a.aspx


private void Button1_Click(object sender, System.EventArgs e) 
{ 
  string s_url; 
  s_url = "b.aspx?name=" + Label1.Text; 
  Response.Redirect(s_url); 
}
Copy after login


 (2)b. aspx


private void Page_Load(object sender, EventArgs e) 
{ 
  Label2.Text = Request.QueryString["name"]; 
}
Copy after login


## 

二、Session

This must be the most common usage among everyone. Its operation is similar to that of Application, and it affects individual users. Therefore, excessive storage will cause the exhaustion of server memory resources.

 

Advantages: 1. Easy to use, not only can pass simple data types, but also objects.   2. The amount of data is not limited.

 

Disadvantages: 1. Storing a large amount of data in Session variables will consume more server resources.

   2. Easy to lose.

 

Usage: 1. Create the name and value you need to pass in the code of the source page to construct the Session variable: Session["Name"]="Value(Or Object)";

      2. Use the Session variable in the code of the destination page to retrieve the passed value. Result = Session["Nmae"]

 

Note:You can destroy the session when it is not in use. The method of destruction is: clear one: Session.Remove("session name");

        Clear all: Session.Clear();

 

Example:(1)a.aspx


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


 (2)b.aspx


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


3. Cookie

 This is also a commonly used method. Cookies are used to store small pieces of information on the user's browser and save the user's relevant information, such as when the user visits a website. ID, user preferences, etc., the user can obtain previous information through retrieval on the next visit. So cookies can also pass values ​​between pages. Cookies are passed back and forth between the browser and the server via HTTP headers. Cookies can only contain string values. If you want to store integer values ​​in Cookie, you need to convert them to string form first.

Like Session, it is for each user, but there is an essential difference, that is, Cookie is stored on the client side, while Session is stored on the server side. And the use of cookies must be used in conjunction with the ASP.NET built-in object Request.

 

Advantages: 1. Simple to use, it is a very common method to maintain user status. For example, in a shopping website, it can be used to maintain user status when users span multiple page forms.

 

Disadvantages: 1. It is often criticized for being used to collect user privacy.

  2. The security is not high and it is easy to forge.

 

 

Usage:1. Create the name and value you need to pass in the code of the source page to construct the Cookie object:


HttpCookie objCookie = new HttpCookie("myCookie","Hello,Cookie!");
Response.Cookies.Add(cookie);
Copy after login


                                     around down through through the code using the Cookie object to retrieve the passed value: Result = Request.Cookies[ "myCookie" ].Value;

Example: (1)a.aspx


private void Button1_Click(object sender, System.EventArgs e)
{
  HttpCookie objCookie = new HttpCookie("myCookie","Hello,Cookie!");
  Response.Cookies.Add(objCookie); 
}
Copy after login


 (2)b.aspx


string myName1Value;
myName1Value = Request.Cookies[ "myCookie" ].Value;
Copy after login


  四、Application

  Application对象的作用范围是整个全局,也就是说对所有用户都有效。它在整个应用程序生命周期中都是有效的,类似于使用全局变量一样,所以可以在不同页面中对它进行存取。它和Session变量的区别在于,前者是所有的用户共用的全局变量,后者是各个用户独有的全局变量。

  可能有人会问,既然所有用户都可以使用application变量,那他可以用在什么场合呢?这里举个例子:网站访问数。多个请求访问时都可以对它进行操作。

  优点:1.使用简单,消耗较少的服务器资源。

     2.不仅能传递简单数据,还能传递对象。

     3.数据量大小是不限制的。

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

  使用方法:1.在源页面的代码中创建你需要传递的名称和值构造Application变量:Application["Nmae"]="Value(Or Object)";

       2.在目的页面的代码使用Application变量取出传递的值。Result = Application["Nmae"]

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

  例子:(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


 

  五、Server.Transfer

  这个才可以说是面象对象开发所使用的方法,其使用Server.Transfer方法把流程从当前页面引导到另一个页面中,新的页面使用前一个页面的应答流,所以这个方法是完全面象对象的,简洁有效。

  Server.Transfer是从当前的ASPX页面转到新的ASPX页面,服务器端执行新页并输出,在新页面中通过Context.Handler来获得前一个页面传递的各种数据类型的值、表单数据、QueryString.由于重定向完全在服务器端完成,所以客户端浏览器中的URL地址是不会改变的。调用Server.Transfer时,当前的ASPX页面终止执行,执行流程转入另一个ASPX页面,但新的ASPX页面仍使用前一ASPX页面创建的应答流。

  ps:比较Server.Transfer和Response.Redirect的区别。
    (1)Server.Transfer在服务器端完成,所以客户端浏览器中的URL地址是不会改变的;Response.Redirect是客户端完成,向服务器端提出新的页面处理请求,所以客户端浏览器中的URL地址是会改变的。
    (2)Server.Transfer在服务器端完成,不需要客户端提出请求,减少了客户端对服务器端提出请求。[2]
    (3)Server.Transfer只能够转跳到本地虚拟目录指定的页面,也就是工程项目中的页面,而Response.Redirect则十分灵活,可以跳转到任何URL地址。
    (4)Server.Transfer可以将前一个页面的各种类型的值传到新的页面;Response.Redirect则只能借助URL中带参数或是结合上面四种办法把各种类型的值传到新的页面。

  优点:1.直接在服务器端重定向,使用简单方便,减少了客户端对服务器端提出请求。

     2.可以传递各种数据类型的值和控件的值。

  缺点:1.客户端浏览器中的URL地址是不改变,会导致在新的页面可能出现一些意想不到的问题。比如如果源页面和目的页面不在同一个虚拟目录或其子目录下,那么使用相对路径的图片、超链接都会导致错误的指向。

  使用方法:1.在源页面的代码中,使用Page类的Server.Transfer跳到另一个页面传递页面数据:Server.Transfer("b.aspx","false")。

       2.在目的页面中,使用Context.Handler来接收数据:FormerPage formerPage = (FormerPage)Context.Handler; 然后用formerPage的属性和方法来获取前一个页面的值,或者直接用Context.Items["myParameter "]

  例子:(1)a.aspx


public string Name 
{ 
  get{ return Label1.Text;} 
} 
private void Button1_Click(object sender, System.EventArgs e) 
{ 
  Server.Transfer("b.aspx"); 
}
Copy after login


    (2)b.aspx


private void Page_Load(object sender, EventArgs e) 
{ 
  a newWeb; //实例a窗体   newWeb = (source)Context.Handler; 
  string name; 
  name = newWeb.Name; 
}
Copy after login


 

The above are several methods commonly used by ASP.NET to transfer values ​​between pages. I usually use session and querystring to transfer values. In a few cases, cookies are used. This article only introduces the use of these methods. There is not much explanation of the internal principles. For the storage method of session, please see: session storage method and configuration file


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

Is C# .NET Right for You? Evaluating its Applicability Is C# .NET Right for You? Evaluating its Applicability Apr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# .NET and the Future: Adapting to New Technologies C# .NET and the Future: Adapting to New Technologies Apr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Apr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# and the .NET Runtime: How They Work Together C# and the .NET Runtime: How They Work Together Apr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# and .NET: Understanding the Relationship Between the Two C# and .NET: Understanding the Relationship Between the Two Apr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

See all articles