View status and control status on the page

Source: Internet
Author: User

This example shows how to createIndexbuttonThe custom control that maintains key status information between multiple page requests using the control status. The control State introduced in ASP. NET 2.0 is similar to the view state, but its function is independent of the view State. Webpage developers may disable the view status of the entire page or a single control for performance reasons, but they cannot disable the control status. The control status is designed to store important data of a control (such as the number of pages of a page control, this data must be used for the control to work properly (even if the view status is disabled ). By default, the ASP. NET page framework stores the control status in a hidden element of the page, and the view status is also stored in this hidden element. Even if the view status is disabled or the session management status is used, the control status on the page is still transmitted to the client and then returned to the server. When sending a response, ASP. NET deserializes the content of the hidden elements and loads the control status to each control that has registered the control status.

Note:

Use the control status only for a small amount of key data that is critical to the control during the sending-back process, instead of using the control status as a backup option for the view status.

This example illustrates a custom control that saves the status in both the control status and view status. In this example,IndexbuttonControls are derived from the button class andIndexAnd save the property in the control status. For comparison,IndexbuttonAlso definesIndexinviewstateAttribute, which is stored in the viewstate dictionary. To understand the differences between the control status and view status, use the. ASPX page listed in the "test page of The indexbutton control" section next to this topic to demonstrateIndexbuttonControl.

Code List of the indexbutton Control

VB C #C ++ F # JScript Replication
// IndexButton.csusing System;using System.ComponentModel;using System.Security.Permissions;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Samples.AspNet.CS.Controls{    [    AspNetHostingPermission(SecurityAction.Demand,        Level = AspNetHostingPermissionLevel.Minimal),    AspNetHostingPermission(SecurityAction.InheritanceDemand,         Level=AspNetHostingPermissionLevel.Minimal),    ToolboxData("<{0}:IndexButton runat=/"server/"> </{0}:IndexButton>")    ]    public class IndexButton : Button    {        private int indexValue;        [        Bindable(true),        Category("Behavior"),        DefaultValue(0),        Description("The index stored in control state.")        ]        public int Index        {            get            {                return indexValue;            }            set            {                indexValue = value;            }        }        [        Bindable(true),        Category("Behavior"),        DefaultValue(0),        Description("The index stored in view state.")        ]        public int IndexInViewState        {            get            {                object obj = ViewState["IndexInViewState"];                return (obj == null) ? 0 : (int)obj;            }            set            {                ViewState["IndexInViewState"] = value;            }        }        protected override void OnInit(EventArgs e)        {            base.OnInit(e);            Page.RegisterRequiresControlState(this);        }        protected override object SaveControlState()        {            // Invoke the base class's method and            // get the contribution to control state            // from the base class.            // If the indexValue field is not zero            // and the base class's control state is not null,            // use Pair as a convenient data structure            // to efficiently save             // (and restore in LoadControlState)            // the two-part control state            // and restore it in LoadControlState.            object obj = base.SaveControlState();            if (indexValue != 0)            {                if (obj != null)                {                    return new Pair(obj, indexValue);                }                else                {                    return (indexValue);                }            }            else            {                return obj;            }        }        protected override void LoadControlState(object state)        {            if (state != null)            {                Pair p = state as Pair;                if (p != null)                {                    base.LoadControlState(p.First);                    indexValue = (int)p.Second;                }                else                {                    if (state is int)                    {                        indexValue = (int)state;                    }                    else                    {                        base.LoadControlState(state);                    }                }            }        }    }}
Code Discussion

IndexbuttonThe implementation of the control illustrates three tasks. You must execute these three tasks to make the control participate in the control status:

  • Override the oninit method and call the registerrequirescontrolstate method to register with the page to participate in the control status. This task must be completed for each request.

  • Override the savecontrolstate method to save data in the control state.

  • Override the loadcontrolstate method to load data from the control state. This method calls the base class method and obtains the Base Value of the base class to the control status. IfIndexvalueThe field is not zero, and the control status of the base class is not empty. The pair class can be used as a convenient data structure to save and restore the control status composed of two parts.

Test page of The indexbutton Control

The following example illustrates a page that sets the enableviewstate attributeFalseTo disable the view status. Use this pageIndexbuttonControl, andPage_loadIn the event handlerIndexAndIndexinviewstateAdd 1 to the attribute value. Tab displayIndexAndIndexinviewstateThe values of the two attributes.

BecauseIndexProperties are stored in the control status that cannot be disabled. ThereforeIndexAttribute will maintain its value at the time of sending back, and Add 1 each time the page is sent back to the server. In contrast, becauseIndexinviewstateAttributes are stored in the view status, and the view status of the page has been disabled.IndexinviewstateThe default value is zero.

VB C #C ++ F # JScript Replication
<%@ Page Language="C#" Trace="true" EnableViewState="false" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">  void Page_Load(object sender, EventArgs e)  {    Label1.Text = (IndexButton1.Index++).ToString();    Label2.Text = (IndexButton1.IndexInViewState++).ToString();  }</script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.