ASP.NET How ViewState works

后端 未结 3 1003
攒了一身酷
攒了一身酷 2020-12-06 19:57

I have a textbox and button on my .aspx page. The EnableViewState property of the textbox is set to false. But when I enter some text in the textbox and click the button the

3条回答
  •  情书的邮戳
    2020-12-06 20:18

    Take a look at Server controls persist their state when EnableViewState is set to False

    The following server controls persist their information across requests even when the control ViewState (the EnableViewState attribute) is set to False:

    • The TextBox control.
    • The CheckBox control.
    • The RadioButton control.

    This behavior occurs because the ViewState of a control is only one of the methods that are used to persist a control's attributes across requests. In the server controls that are mentioned, attributes that are not normally posted to the server through the form-get or the form-post are handled by the ViewState. These values include attributes of the control, such as BackColor.

    Attributes that are normally posted to the server are handled by the IPostBackDataHandler interface. An example of such an attribute is the checked attribute of the CheckBox control.

    Example: Consider backcolor setting programmatically. On postback, if viewstate is switched off, the background color of the Textbox control is lost. However, the text value of the control is maintained.

    Note: If the backcolor was set directly in markup rather than in code behind, it would have persisted.

    protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { this.Textbox1.BackColor = Color.Yellow; } }

    Following is from Understanding ASP.NET View State:

    It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler.

    A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data.

    Also refer following

    1. View State for TextBox and other controls that implement IPostBackDataHandler

    2. How do I disable viewstate for a specific control?

提交回复
热议问题