Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
New Feature: Community Sites:
Create your own .NET community website and start earning from Google AdSense !
It's Free !
|
viewstate
Posted Date:
15 Jul 2008
Total Responses:
6
|
Posted By: usharani Member Level: Silver Points: 1
|
how to create viewstate using asp.net with vb.net application
|
Responses
|
| Author: venkatesan 15 Jul 2008 | Member Level: Diamond | Rating: Points: 6 | Hai Good Morning
ViewState > The root of all causes is the statelessness of web
• The web is a stateless medium – state is not maintained between client requests by default. • ASP.NET provides several mechanisms to manage state in a more powerful and easier to utilize way than classic ASP or other web programming languages.
Scenario
You submit the form with data; and the server comes back saying there's an error and you need to go back and enter data again.
You click the back button in browser and you realize all the entries you typed are now gone and now; you have to start all over! Did you maintain, ViewState. ?
ViewState is the mechanism by which page state (information) is maintained between page post backs, i.e. a web form is submitted by the user and then this page performs some processing and perhaps presents further information to the user.
Before ASP.NET, restoring the values back into the form fields across multiple postbacks was entirely the responsibility of the page developer, who had to pick them out, one-by-one, from the HTTP form, and push them back into the fields.
How ViewState Works
• It's a hidden form field managed by the ASP.NET page framework. • When ASP.NET executes a page, the ViewState values from the page and all of the controls are collected and formatted into a single encoded string, and then assigned to the value attribute of the hidden form field (specifically, ). • Since the hidden form field is part of the page sent to the client, the ViewState value is temporarily stored in the client's browser. If the client chooses to post the page back to the server, the ViewState string is posted back too. • controls maintain their state via hidden form fields • In essence the server is sending the state of the form along with the form each time it's sent back to the client in the form of this hidden field.
Features of ViewState
• A way to track the state of a control across postbacks • It doesn't use server resources • Doesn't time out • Works with any browser
ViewState Vs. Session State ?
There are certain cases where holding a state value in ViewState is not the best option.
The most commonly used alternative is Session state, which is generally better suited for:
• Large amounts of data.
Since ViewState increases the size of both the page sent to the browser (the HTML payload) and the size of form posted back, it's a poor choice for storing large amounts of data.
• Sensitive data that is not already displayed in the UI.
While the ViewState data is encoded, your data is most secure if it is never sent to the client. So, Session state is a more secure option.
Performance & ViewState
Each object must be serialized going into ViewState and then deserialized upon post back, so there is a performance cost of using ViewState.
ViewState is enabled by default, and is available with each control (Server or Web Control).
Sometimes, ViewState information is not useful to your application. While it's not harmful either, it can dramatically increase the size of the page sent to the browser. It's a good idea to turn off ViewState if you are not using it. Disable ViewState when you don't need it.
• Use the fewest number of objects, and if possible, reduce the number of objects you put into ViewState. • You can turn off ViewState on a per-control, per-page, or even per-application basis. You don't need ViewState if, for example: The page doesn't post back to itself.
Code Snippet
Copy the contents of form1.aspx to \inetpub\wwwroot
Form1.aspx
This code does not maintain the state, after clicking on submit, it will show blank name textbox and C# in technology list.
<%@ Page Language="VB" %> <script runat="server"> Sub Page_Load(Sender As Object, E As EventArgs) If Request.Form("txtName") <> "" Then lblSentence.Text = Request.Form("txtName") _ & " selected " & Request.Form("Technology") End If End Sub </script>
<html><head> <title>ASP.NET Viewstate Form Sample #1</title> </head><body bgcolor="#FFFFFF">
<form action="form1.aspx" method="post">
Enter Your Name: <input type="text" id="txtName" name="txtName" />
Pick your Technology: <select id="technology" name="technology"> <option>C# </option> <option>C++ </option> <option>Java </option> <option>VB</option> <option>C</option> <option>J# </option> <option>Cobol</option> </select>
<input type="submit" id="btnSubmit" text="Submit" /> </form> <asp:label id="lblSentence" runat="server" /> </body> </html>
ViewState.aspx
This code maintains the state, after clicking on submit, textbox and technology list maintains data even after posting the query.
<%@ Page Language="VB" %> <script runat="server"> Sub btnSubmit_Click(Sender As Object, E As EventArgs) lblSentence.Text = txtName.Text & " selected " _ & technology.SelectedItem.Text End Sub </script>
<html> <head> <title>ASP.NET Viewstate Form Sample #2</title> </head> <body bgcolor="#FFFFFF">
<form id="frmViewState" action="form1.aspx" method="post" runat="server">
Enter Your Name: <asp:TextBox id="txtName" runat="server" />
Pick a Color: <asp:DropDownList id="technology" runat="server"> <asp:ListItem>C#</asp:ListItem> <asp:ListItem>C++</asp:ListItem> <asp:ListItem>Java</asp:ListItem> <asp:ListItem>VB</asp:ListItem> <asp:ListItem>C</asp:ListItem> <asp:ListItem>J#</asp:ListItem> <asp:ListItem>Cobol</asp:ListItem> </asp:DropDownList>
<asp:button id="btnSubmit" text="Submit" onClick="btnSubmit_Click" runat="server" />
</form>
<asp:label id="lblSentence" runat="server" />
</body> </html>
Note: RATE this Response.
| | Author: venkatesan 15 Jul 2008 | Member Level: Diamond | Rating: Points: 3 | Ex:
webform1
viewstate("uname")=Textuname.Text
with in the same page u retrive the viewstate value , when the postback occurs..
dim s as string s=viewstate("uname")
It retain value within the page not one page to other page..
| | Author: Ratheesh 15 Jul 2008 | Member Level: Gold | Rating: Points: 1 | The web is a stateless medium – state is not maintained between client requests by default. Technologies must be utilized to provide some form of state management if this is what is required of your application, which will be the case for all but the simplest of web applications. ASP.NET provides several mechanisms to manage state in a more powerful and easier to utilize way than classic ASP.
Page level state is information maintained when an element on the web form page causes a subsequent request to the server for the same page – referred to as 'postback'. This is appropriately called ViewState as the data involved is usually, though not necessarily, shown to the user directly within the page output.
The Control.ViewState property is associated with each server control in your web form and provides a dictionary object for retaining values between such multiple requests for the same page. This is the method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.
ViewState is enabled by default so if you view a web form page in your browser you will see a line similar to the following near the form definition in your rendered HTML:
<input type="hidden" name="__VIEWSTATE" value="dDwxNDg5OTk5MzM7Oz7DblWpxMjE3ATl4Jx621QnCmJ2VQ==" />
When a page is re-loaded two methods pertaining to ViewState are called: LoadViewState and SaveViewState. Page level state is maintained automatically by ASP.NET but you can disable it, as necessary, by setting the EnableViewState property to false for either the controls whose state doesn't need to be maintained or for the page as a whole. For the control:
<asp:TextBox id=”tbName” runat=”server” EnableViewState=”false” />
for the page:
<%@ Page EnableViewState=”false” %>
You can validate that these work as claimed by analyzing the information presented if you turn on tracing for a page containing the above elements. You will see that on postback, and assuming ViewState is enabled, that the LoadViewState method is executed after the Init method of the Page class has been completed. SaveViewState is called after PreRender and prior to actual page rendering.
You can also explicitly save information in the ViewState using the State Bag dictionary collection, accessed as follows:
ViewState(key) = value
Which can then be accessed as follows:
Value = ViewState(key)
It is important to remember that page level state is only maintained between consecutive accesses to the same page. When you visit another page the information will not be accessible via the methods above. For this we need to look at other methods and objects for storing state information, typically session state if the information is required on a per user basis.
| | Author: Kumar Velu 15 Jul 2008 | Member Level: Diamond | Rating: Points: 6 | When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. The source could look something like this:
<form name="_ctl0" method="post" action="page.aspx" id="_ctl0"> <input type="hidden" name="__VIEWSTATE" value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />.....some code</form>
storing content in viewstate:
in vb.net: ViewState("Value")=txtValue.Text in c# ViewState["Value"]=txtValue.Text;
Retrieving content from viewstate
in vb.net: txtValue.Text=ViewState("Value")
in c# txtValue.Text=(string)ViewState["Value"];
| | Author: chandramohan 15 Jul 2008 | Member Level: Gold | Rating: Points: 1 | View State As I mentioned briefly in the previous section, ASP.NET controls automatically retain their data when a page is sent to the server by a user clicking a submit button. Microsoft calls this persistence of data view state. In the past, developers would have to hack a way to remember the item selected in a drop-down menu or keep the contents of a text box, typically using a hidden form field. This is no longer the case; ASP.NET pages, once submitted to the server for processing, automatically retain all information contained within text boxes, items selected within drop-down menus, radio buttons, and check boxes. Even better, they keep dynamically generated tags, controls, and text. Consider the following ASP page, called sample.asp:
<html> <head> <title>Sample Page using VBScript</title> </head> <body> <form method="post" action="sample.asp"> <input type="text" name="txtName"/> <input type="Submit" name="btnSubmit" text="Click Me"/> <% If Request.Form("txtName") <> "" Then Response.Write(Request.Form("txtName")) End If %>
</form> </body> </html>
If you save this example in the WebDocs subdirectory of wwwroot that you created in Chapter 1, Introduction to .NET and ASP.NET, you can open it in your browser by typing http://localhost/WebDocs/sample.asp, to see that view state is not automatically preserved. When the user submits the form, the information that was previously typed into the text box is cleared, although it is still available in Request.Form("txtName"). The equivalent page in ASP.NET, ViewState.aspx, demonstrates data persistence using view state:
Example 2.1. ViewState.aspx
<html> <head> <title>Sample Page using VB.NET</title> <script runat="server" language="VB"> Sub Click(s As Object, e As EventArgs) lblMessage.Text = txtName.Text End Sub </script> </head>
<body> <form runat="server"> <asp:TextBox id="txtName" runat="server" /> <asp:Button id="btnSubmit" Text="Click Me" OnClick="Click" runat="server" /> <asp:Label id="lblMessage" runat="server" /> </form> </body> </html>
Example 2.2. ViewState.aspx
<html> <head> <title>Sample Page using C#</title> <script runat="server" language="C#"> void Click(Object s, EventArgs e) { lblMessage.Text = txtName.Text; } </script> </head>
<body> <form runat="server"> <asp:TextBox id="txtName" runat="server" /> <asp:Button id="btnSubmit" Text="Click Me" OnClick="Click" runat="server" /> <asp:Label id="lblMessage" runat="server" /> </form> </body> </html>
In this case, the code uses ASP.NET controls with the runat="server" attribute. As you can see in Figure 2.2, the text from the box appears on the page when the button is clicked, but also notice that the data remains in the text box --------------
The web is a stateless medium – state is not maintained between client requests by default. Technologies must be utilized to provide some form of state management if this is what is required of your application, which will be the case for all but the simplest of web applications. ASP.NET provides several mechanisms to manage state in a more powerful and easier to utilize way than classic ASP.
Page level state is information maintained when an element on the web form page causes a subsequent request to the server for the same page – referred to as 'postback'. This is appropriately called ViewState as the data involved is usually, though not necessarily, shown to the user directly within the page output.
The Control.ViewState property is associated with each server control in your web form and provides a dictionary object for retaining values between such multiple requests for the same page. This is the method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.
ViewState is enabled by default so if you view a web form page in your browser you will see a line similar to the following near the form definition in your rendered HTML:
<input type="hidden" name="__VIEWSTATE" value="dDwxNDg5OTk5MzM7Oz7DblWpxMjE3ATl4Jx621QnCmJ2VQ==" />
When a page is re-loaded two methods pertaining to ViewState are called: LoadViewState and SaveViewState. Page level state is maintained automatically by ASP.NET but you can disable it, as necessary, by setting the EnableViewState property to false for either the controls whose state doesn't need to be maintained or for the page as a whole. For the control:
<asp:TextBox id=”tbName” runat=”server” EnableViewState=”false” />
for the page:
<%@ Page EnableViewState=”false” %>
You can validate that these work as claimed by analyzing the information presented if you turn on tracing for a page containing the above elements. You will see that on postback, and assuming ViewState is enabled, that the LoadViewState method is executed after the Init method of the Page class has been completed. SaveViewState is called after PreRender and prior to actual page rendering.
You can also explicitly save information in the ViewState using the State Bag dictionary collection, accessed as follows:
ViewState(key) = value
Which can then be accessed as follows:
Value = ViewState(key)
It is important to remember that page level state is only maintained between consecutive accesses to the same page. When you visit another page the information will not be accessible via the methods above. For this we need to look at other methods and objects for storing state information, typically session state if the information is required on a per user basis.
Following this initial overview let’s consider several ViewState related topics in more detail.
Postback and non-postback controls Some server controls, for example the textbox control, post their values as part of the postback operation and are known as postback controls. For such postback controls ASP.NET retrieves their values one by one from the HTTP Request and copies them to control values whilst creating the HTTP Response. Traditionally, web developers had to write code to do all this but now ASP.NET handles these activities automatically. Importantly there are no extra storage overheads for ViewState in maintaining state for postback controls.
In addition ViewState also supports non-postback controls, e.g. Label controls. This is where the hidden fields are used to maintain state. When ASP.NET executes a page, it collects the values of all non-postback controls that are modified in code and formats them into a single base64-encoded string. This string is then stored in a hidden file in a control named __VIEWSTATE, as per the example above. The hidden field is a postback control and when the encoded string is processed by the web server ASP.NET decodes the string at page initialisation and restores the controls values to the page.
What can you store in ViewState? ViewState offers a substantial improvement over the two competing techniques for state management via the client: standard hidden fields and cookies, in that ViewState is not limited to the storage of simple values. You can use ViewState to store any object as long as it is serializable, and the standard VB.NET types are. Serialization is the process of storing an object's data and other information necessary to reconstruct the object later.
There is a further complication: a type that either is serializable or has a TypeConverter defined for it can be persisted in ViewState. However, types that are only serializable are slower and generate a much larger ViewState than those that have a TypeConverter. The TypeConverter class provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties.
ViewState is serialized using a limited object serialization format that is optimized for primitive types, and for String, ArrayList, and HashTable types. You may want to consider these issues if page performance concerns are key – see the section on performance below.
Protecting ViewState By default the ViewState of a page is unprotected. Although the values are not directly visible as in the case of querystring or hidden form fields, it would not be too difficult for a determined individual to decode the stored information. However, Microsoft has provided two mechanisms for increasing the security of ViewState.
Machine Authentication Check (MAC) - tamper-proofing In fact tamper-proofing does not protect against an individual determining the contents of the ViewState. It instead provides a way of detecting whether someone has modified the contents of the ViewState in an attempt to deceive your application. In this technique the ViewState is encoded using a hash code (using the SHA1 or MD5 algorithms) before it is sent to the client browsers. On postback ASP.NET checks the encoded ViewState to verify it has not been tampered with. This is called a machine authentication check and is simply enabled at the page level:
<%@ Page EnableViewStateMac="true"%>
However, MAC is enabled by default in the machine.config file so should not be a concern unless someone has altered the default settings.
Encrypting the ViewState You can instruct ASP.NET to encrypt the contents of ViewState using the Triple DES symmetric algorithm (see the .NET SDK documentation for more information) – a stronger encryption algorithm that makes it very difficult for anyone to decode the ViewState.
This encryption can only be applied at the machine.config level, as follows:
<machineKey validation=’3Des’ />
Note: if securing ViewState in a web farm scenario (multiple servers running the same application and thus needing to share state information) you must use the same validation key for all servers which is used to encrypt and decrypt the data. To do this you need to explicitly specify a common key rather than relying on autogeneration of a key as per the above configuration line. See the referenced 'Taking a Bite Out of ASP.NET ViewState' article for further information on this area.
ViewState and Performance By default ViewState is enabled in an ASP.NET application. Developers should be aware that any data in ViewState automatically makes a round trip to the client. Because the round trips contribute to a performance overhead, it is important to make judicious use of ViewState.
This is especially important when your application contains complex controls such as a DataList or DataGrid but is generally true when you are presenting considerable information via a server control. An example might be presented a list of countries for selection ... you don't want to impose the overhead of transferring all the country text back and forth from server to client and vice versa more than is strictly necessary. It will significantly impact on response times if you don't disable the ViewState either for the page as a whole or for the specific controls causing the unnecessary overhead.
Whenever you complete a web forms page you should review the controls in the page and consider what is being passed in the ViewState and whether you really need all that information to be passed. To optimise Web page size you may want to disable ViewState in the following cases, amongst others:
when a page does not postback to itself when there are no dynamically set control properties when the dynamic properties are set with each request of the page ASP.NET provides you with complete flexibility to disable ViewState. As already discussed you are able to disable ViewState at the control and page level. Additionally you may disable ViewState at the application and machine level via the web.config and machine.config files via the following directive:
<Pages enableViewState="false"/>
Session State or ViewState? There are certain cases where holding a state value in ViewState is not the best option. The most commonly used alternative is Session state, which is generally better suited for:
Large amounts of data. As ViewState increases the size of both the HTML page sent to the browser and the size of form posted back, it's a poor choice for storing large amounts of data. Sensitive data that is not already displayed in the UI. While the ViewState data is encoded and may optionally be encrypted, your data is most secure if it is never sent to the client. So, Session state is a more secure option. Objects not readily serialized into ViewState, for example, DataSet. As already discussed the ViewState serializer is optimized for a small set of common object types. Other types that are serializable may be persisted in ViewState, but are slower and can generate a very large ViewState
------------
Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. Viewstate stores the state of controls in HTML hidden fields. In other words, it is a snapshot of the contents of a page. When set to True, the ‘EnableViewState’ property enables storing the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. Because it is a Base64 encoded string, it is not readable by the human eye. However it is also not difficult to decode the viewstate and view the contents of the viewstate when it is passed over the wire. In this article we will see how to decode and view the contents of a viewstate. Step 1: Create an asp.net application with 2 textboxes, a label and a button as shown below. On the button click, we will concatenate the values of the 2 textbox and display this information in the label control. <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <br /> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <br /> <br /> <asp:Label ID="Label1" runat="server"></asp:Label><br /> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> <br /> </div> </form> </body> Step 2: Add the button click event: C# protected void Button1_Click(object sender, EventArgs e) { Label1.Text = TextBox1.Text + " " + TextBox2.Text; } VB.NET Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Label1.Text = TextBox1.Text & " " & TextBox2.Text End Sub Step 3: Execute the page and enter some values in the textbox. We will enter the value ‘I Love’ and ‘Dotnetcurry.com’ respectively in the two textboxes. Now click the button. The label will contain the concatenated value and should display ‘I Love Dotnetcurry.com’. Now right click on the page > View Source. Along with the other html text, you will see the following: <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODczNjQ5OTk0D2QWAgIDD2QWAgIFDw8WAh4EV GV4dAUWSSBMb3ZlIERvdG5ldEN1cnJ5LmNvbWRkZMHbBY9JqBTvB5 /6kXnY15AUSAwa" /> Step 4: Shown above in the blue colored text is the viewstate. This is the Base64 encoded string which we will be decoding. Do the following. Add another textbox and button control on to the page. Rename the textbox to ‘txtViewState’ and set its ‘TextMode’ property to ‘Multiline’. Set the text property of the button control to ‘View ViewState’ as shown below: <br />View State<br />
<asp:TextBox ID="txtViewState" runat="server" TextMode="MultiLine" Width="667px"></asp:TextBox><br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="View ViewState" />
On the button click add the following code. C# protected void Button2_Click(object sender, EventArgs e) { byte[] decode = Convert.FromBase64String(txtViewState.Text); txtViewState.Text = System.Text.Encoding.ASCII.GetString(decode); } VB.NET Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Dim decode As Byte() = Convert.FromBase64String(txtViewState.Text) txtViewState.Text = System.Text.Encoding.ASCII.GetString(decode) End Sub Step 5: Repeat Step 3. Copy the blue colored text and paste it in the ‘txtViewState’ textbox. Now click on the second button ‘View ViewState’. You will see that the decoded viewstate is displayed in the textbox as shown below: ? 873649994d[1][1] d[1][1][1]- TextI Love DotnetCurry.comddd???I?????y???H Even though there are junk characters displayed in the textbox, however you can make out that the textbox contained the word ‘I Love DotnetCurry.com’ Well that was simple, wasn’t it? In the coming articles we will see how to encrypt viewstate in order to prevent its contents to be decoded
| | Author: asdf 14 Aug 2008 | Member Level: Silver | Rating: Points: 0 | • View state To retain the STATE of the server side objects BETWEEN postbacks by storing in hidden field on the page. View state is available – after init() or before Page Load() or beore On Load() For a control.
|
| Post Reply |
|
|
|
You must Sign In to post a response.
|
|
|
|