Monday, June 28, 2010

VIEW STATE-C#

VIEW STATE-C#
ViewState is the mechanism that allows state values to be preserved across page postbacks.
Because of the stateless nature of web pages, regular page member variables will not maintain their values across postbacks. When we need a page variable to maintain its value across page post backs, we can use ViewState to store that value. Values stored in ViewState will be serialized and sent to the client browser as the value of a hidden form input. When you view the page source (in your browser) of a page the uses ViewState, you may see this hidden viewstate input which will look something like this:

This single hidden field contains all the viewstate values for all the page controls. This is an important aspect of viewstate that you need to consider.
Because viewstate is (by default) sent to the client browser and then returned to the server in the form of a hidden input control on your page, storing a significant amount of data in viewstate can increase your page size and can affect your page performance.
To disable ViewState for a control, you can set the EnableViewState property to false. When ViewState is disabled for any control, it will also automatically be disabled for all child controls of that control.
Example:

This does not mean that you should avoid viewstate. You should however, always be aware of what you are storing there and how it affects your overall page size.
Some people hate ViewState, others love it. Either way, you have control over your ViewState, so take control!
Example
One simple way to store small values in viewstate is to use a property instead of a member variable. This property can use viewstate to store its value rather than a member variable that would lose the value over a postback. For example, storing an Integer in viewstate can be accomplished like this:
VB
Public Property SomeInteger() As Integer
Get
Dim o As Object = ViewState("SomeInteger")
If Not o Is Nothing Then Return DirectCast(o, Integer)
Return 0 'a default
End Get
Set(ByVal value As Integer)
ViewState("SomeInteger") = value
End Set
End Property
C#
public int SomeInteger {
get {
object o = ViewState["SomeInteger"];
if (o != null) return (int)o;
return 0;
//a default
}
set { ViewState["SomeInteger"] = value; }
}

This step-by-step article describes how to control the caching of Web pages and data objects in ASP.NET. When you cache Web pages, you avoid re-creating information when you make a later request. Caching is an important technique for building high performance and scalable server applications. When you make the first request for the page, you can store data objects, pages, or part of the page to the memory. You can store these items on a Web server, on a proxy server, or on the browser.



Back to the top
MORE INFORMATION
ASP.NET provides easier methods to control caching. You can use the @ OutputCache directive to control page output caching in ASP.NET. Use the HttpCachePolicy class to store arbitrary objects, such as datasets, to server memory. You can store the cache in applications such as the client browser, the proxy server, and Microsoft Internet Information Services (IIS). By using the Cache-Control HTTP Header, you can control caching.

For more information about ASP.NET output caching, click the following article number to view the article in the Microsoft Knowledge Base:
308375 How to control page output caching in ASP.NET by using Visual C# .NET


Back to the top
Cache ASP.NET pages

You can use the @ OutputCache directive to cache, or you can cache programmatically through code by using Visual Basic .NET or Visual C# .NET. The @ OutputCache directive contains a Location attribute. This attribute determines the location for cached item. You can specify the following locations:
• Any - This stores the output cache in the client's browser, on the proxy server (or any other server) that participates in the request, or on the server where the request is processed. By default, Any is selected.
• Client - This stores output cache in the client's browser.
• Downstream - This stores the output cache in any cache-capable devices (other than the origin server) that participate in the request.
• Server - This stores the output cache on the Web server.
• None - This turns off the output cache.

The following are code samples for the @ OutputCache directive and equivalent programmatic code.
• To store the output cache for a specified duration

Declarative Approach:
<%@ OutputCache Duration="60" VaryByParam="None" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
• To store the output cache on the browser client where the request originated

Declarative Approach:
<%@ OutputCache Duration="60" Location="Client" VaryByParam="None" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Private);
• To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request

Declarative Approach:
<%@ OutputCache Duration="60" Location="Downstream" VaryByParam="None" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetNoServerCaching();
• To store the output cache on the Web server

Declarative Approach:
<%@ OutputCache Duration="60" Location="Server" VaryByParam="None" %>

Programmatic Approach:
TimeSpan freshness = new TimeSpan(0,0,0,60);
DateTime now = DateTime.Now;
Response.Cache.SetExpires(now.Add(freshness));
Response.Cache.SetMaxAge(freshness);
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);
• To cache the output for each HTTP request that arrives with a different City:

Declarative Approach:
<%@ OutputCache duration="60" varybyparam="City" %>

Programmatic Approach:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByParams["City"] = true;
For the VaryByCustom attribute, the VaryByHeader attribute, and the VaryByParam attribute in the @ OutputCache directive, the HttpCachePolicy class provides the VaryByHeaders property and the VaryByParams property, and the SetVaryByCustom method.


Back to the top
Turn off client and proxy caching
To turn off the output cache for an ASP.NET Web page at the client location and at the proxy location, set the Location attribute value to none, and then set the VaryByParam value to none in the @ OutputCache directive. Use the following code samples to turn off client and proxy caching.
• Declarative Approach:
<%@ OutputCache Location="None" VaryByParam="None" %>
• Programmatic Approach:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Back to the top
Cache arbitrary objects in server memory
ASP.NET includes a powerful, easy-to-use caching mechanism that you can use to store objects that require a lot of server resources to create in memory. The Cache class implements this method. Instances are private to each application and the lifetime is tied to the corresponding application. To cache the arbitrary objects in ASP.Net by using the Cache class, follow these steps:
1. Create a new ASP.NET Web Application by using Visual C# .NET.
2. By default, WebForm1.aspx is created.
3. In HTML view of WebForm1.aspx, replace the existing code with the following sample code:
4. <%@ Import Namespace="System.Data" %>
5. <%@ Import Namespace="System.Data.SqlClient" %>
6.
7. Note Replace the values for ServerName, UID, and PWD in the sample code for the SqlConnection object with your SQL Server Name, User ID, and Password.
68. On the Debug menu, click Start to run the application.

Note When you restart the application, the Cached object is re-created.
Introduction
Before I start this article, let me ask you something. Is it possible to access the ViewState variable of one page on another page? I don't know what your answer is. Well, frankly speaking, my answer was also "NO" before writing this article as it is said that ViewState is page specific.
Background
ViewState is a very misunderstood animal. It is said that ViewState is Page specific; that means, it is available only on the same page on which it was created. Once you redirect to another page, the previous page's viewstate is no longer accessible. But that is not true.
Using the Code
Yes, we can access the viewstate variables across pages. This is only possible if Cross Page Posting or Server.transfer is used to redirect the user to other page. If Response.redirect is used, then ViewState cannot be accessed across pages.
Before you continue reading this article, please read these articles on Cross Page Posting and Server.transfer.
Ok, so all set now... I will demonstrate this using the demo created by me. You can download the demo from the link at the top of this article.
I have created two *.aspx pages named:
1. ViewStateContainer.aspx: This page sets the ViewState variable and transfers the user to another page using Server.transfer.
2. AccessViewState.aspx: This page accesses the ViewState variable of ViewStateContainer.aspx page.
This is the code of ViewStateContainer.aspx page:
Collapse Copy Code
public partial class ViewStateContainer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ViewState["Page1"] = "Page1 ViewState";
Server.Transfer("AccessViewState.aspx");
}

public StateBag ReturnViewState()
{
return ViewState;
}
}
As you can see, I have set a ViewState variable in Page Load and transfer the user to AccessViewState.aspx page using the Server.transfer() method.
This page also contains a method ReturnViewState() which actually returns the ViewState of this page to the calling function. The return type of the method is StateBag class.
StateBag class: This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page's or control's viewstate.
Now let's take look at AccessViewState.aspx Page code:
Collapse Copy Code
public partial class AccessViewState : System.Web.UI.Page
{
private StateBag PreviousPageViewState
{
get
{
StateBag returnValue = null;
if (PreviousPage != null)
{
Object objPreviousPage = (Object)PreviousPage;
MethodInfo objMethod = objPreviousPage.GetType().GetMethod
("ReturnViewState");
return (StateBag)objMethod.Invoke(objPreviousPage, null);
}
return returnValue;
}
}

protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
if (PreviousPageViewState != null)
{
Label1.Text = PreviousPageViewState["Page1"].ToString();
}
}
}
}
Whenever we use Server.transfer or Cross Page Posting, We can get the previous page object via PreviousPage property. Using Previous Page, we can find the controls of the previous page. For example, one can access Label control placed in ViewStateContainer Page in current Page.
Looking at the code, I have created a PreviousPageViewState property in this page, which returns the previous page's ViewState. It first checks whether PreviousPage is null or not, if it's not null, then it creates an object of the previous page. Now using Reflection, we can invoke the method of the previous class. Using MethodInfo class, I have invoked the ReturnViewState() method of ViewStateContainer Page.
In Page_Load event, I am able to access the ViewState variable of ViewStateContainer Page. You can access all the viewstate variables set in ViewStateContainer Page.
Enjoy.

No comments:

Post a Comment