Monday, January 23, 2012

View State

Web Forms pages provide the ViewState property as a built-in structure for automatically retaining values between multiple requests for the same page. View state is maintained as a hidden field in the page.

You can use view state to store your own page-specific values across round trips when the page posts back to itself. 

Each page and each control on the page has View State property. This property allows automatic retention of page and controls state between 
each trip to server. This means control value is maintained between page postbacks. Viewstate is implemented using _VIEWSTATE, a hidden 

form field which gets created automatically on each page. You can't transmit data to other page using view state.

public partial class _Default : System.Web.UI.Page 
    protected void Page_Load(object sender, EventArgs e)
        if(ViewState["Name"] != null)
            NameLabel.Text = ViewState["Name"].ToString();
            NameLabel.Text = "Not set yet!!!";

    protected void SubmitForm_Click(object sender, EventArgs e)
        ViewState["Name"] = NameField.Text;
        NameLabel.Text = NameField.Text;

Advantages of View State :
1: No server resources are required. The view state is contained in a structure within the page code.
2: Simple implementation. View state does not require any custom programming to use. It is on by default to maintain state data on controls.
3: Enhanced security features.  

Disadvantages of View State:
1: Performance considerations   Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.
2: Device limitations. Mobile devices might not have the memory capacity to store a large amount of view-state data.
3: Potential security risks. The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. 

No comments: