Viewstate in ASP.NET

Viewstate:-

Viewstate is used to store the state of server-side controls between the postback of the webpages. Viewstate stores the data within the same page, while the session state is stored in the server. The information is stored in HTML hidden fields. Viewstate is used by enabling or disabling the viewstate properties. It is default for viewstate to be true, but you can disable it by setting the EnableViewState property to false.

Example:-

ViewStatePage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewStatePage.aspx.cs" Inherits="DemoApp.ViewState.ViewStatePage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>
                    <asp:TextBox ID="txtName" runat="server" placeholder="Enter any text"></asp:TextBox>
                    <asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" Text="Click to store data in viewstate and show in textbox" />
                        </td>
                </tr>
                <tr>
                    <td>
                    <asp:Label ID="lblviewstatedata" runat="server" Text="Data Showing with ViewSate"></asp:Label>
                    <asp:TextBox ID="txtviewstatedata" runat="server"></asp:TextBox>
                    </td>
                </tr>
            </table>


        </div>
    </form>
</body>
</html>

ViewStatePage.aspx.cs

using System;
namespace DemoApp.ViewState
{
    public partial class ViewStatePage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {

            }
        }

        protected void btnsubmit_Click(object sender, EventArgs e)
        {
            ViewState["Data"] = txtName.Text;
            txtviewstatedata.Text = ViewState["Data"].ToString();
        }
    }
}

These above are design and code files. When clicked on button the textbox data is stored in viewstate and we can fetch data from viewstate in another textbox as shown below.

Viewstate in ASP.NET
ViewSate in ASP.NET

Advantages
1. Viewstate is simple. It is used by enabling or disabling the viewstate properties.
2. Viewstate doesn't require server resources.
3. Viewstate guarantees security since it stores the data in encrypted format.
4. It is retained automatically.














Post a Comment

0 Comments