ASP. NET custom controls use Star controls in control status on the third day

Source: Internet
Author: User
1. Introduction

As shown in the previous two tasks, viewstate is used to save custom control attributes. viewstate is actually a statebag object, developers use the key/Value Method to save or read settings to the view. The HTML page that is finally sent to the user contains a hidden field, the hidden domain stores serialized values. Excessive use of the view will result in a sharp increase in the page. Although the network bandwidth is no longer a restriction, it is still a poor design, so developers sometimes disable the view status.

If you disable the view status of a custom control, the control may not work properly. You can use the star control developed in the first task, disable the view status of the page (set the enableviewstate attribute of the page command to false) and enter the following in the page loading event:CodeTo set the score:

 
Protected void page_load (Object sender, eventargs e) {If (! Ispostback) Star. Score = 4 ;}

On the ASPX page, place a server button to cause a sending event. preview the page and click the button. What will happen? Because the "Submit" button causes the "send back ispostback" attribute to be true, the score setting operation is not performed. Because the view status is disabled, the score cannot be restored from the view status when running in the page lifecycle, therefore, no score is displayed:

2. Analysis

In. in net1.x, the view status is regarded as a whole. It is inconvenient for control developers to disable or disable the control. control-related data is stored in viewstate. Once disabled, there may be problems. Fortunately, Microsoft responded in a timely manner to this situation. In ASP. net2.0, a new concept emerged: control status.

The control state is actually a special view State. It is still stored in the hidden domain of the client, but it is not affected by the enabling/disabling of the view State, that is, even if the viewstate is disabled, the data stored in the control state can still be correctly restored during running.

To use the control status, you only need to do the following:

    1. Register the control status with the page
    2. Save related data in the control State save event (the savecontrolstate method of the control class)
    3. Read the stored data in the control status read event (the loadcontrolstate method of the control class ).

It should be noted that because the control status is always sent to the client, it is obviously not a good event to save a large amount of data to the control status, always only the key core data that affects the use of the control should be saved.

To enable the control to be normally used after the page view status is disabled, the score of the star control is saved in the control status.

3. Implementation

Create a new class that uses the control status for organizing files.

1. Add the statestar class to the controllibrary class library of the custom control solution, define attributes and create control layers and present them like the first task:

Using system; using system. componentmodel; using system. web. ui; using system. web. UI. webcontrols; namespace controllibrary {public class statestar: webcontrol {private int _ score; [defaultvalue (0)] public int score {get {return _ score ;} set {_ score = value ;}} Public String comment {get {object OBJ = viewstate ["comment"]; return OBJ = NULL? String. empty: convert. tostring (OBJ) ;}set {viewstate ["comment"] = value ;}} protected override void createchildcontrols () {base. createchildcontrols (); createcontrolhierarchy ();} protected virtual void createcontrolhierarchy () {Table = new table (); tablerow ROW = new tablerow (); table. rows. add (ROW); tablecell comment = new tablecell (); createcomment (comment); row. cells. add (comment); tablecell stars = new tablecell (); createstars (stars); row. cells. add (stars); this. controls. add (table );} /// <summary> /// create a comment label to the cell /// </Summary> /// <Param name = "cell"> Cell Object </param> private void createcomment (tablecell cell) {label LBL = new label (); LBL. TEXT = comment; cell. controls. add (LBL );} /// <summary> /// create a star-shaped pattern in the cell /// </Summary> /// <Param name = "cell"> </param> private void createstars (tablecell cell) {string starpath = page. clientscript. getwebresourceurl (this. getType (), "controllibrary.image.stars.gif"); Panel panbg = new Panel (); panbg. style. add (htmltextwriterstyle. width, "80px"); panbg. style. add (htmltextwriterstyle. height, "16px"); panbg. style. add (htmltextwriterstyle. textalign, "Left"); panbg. style. add (htmltextwriterstyle. overflow, "hidden"); panbg. style. add (htmltextwriterstyle. backgroundimage, starpath); panbg. style. add ("background-position", "0px-32px"); panbg. style. add ("background-repeat", "Repeat-X"); cell. controls. add (panbg); Panel pancur = new Panel (); string width = score * 16 + "PX"; pancur. style. add (htmltextwriterstyle. width, width); pancur. style. add (htmltextwriterstyle. height, "16px"); pancur. style. add (htmltextwriterstyle. backgroundimage, starpath); pancur. style. add ("background-position", "0px 0px"); pancur. style. add ("background-repeat", "Repeat-X"); panbg. controls. add (pancur);} protected override void render (htmltextwriter writer) {preparecontrolforreader (); base. render (writer );}}}

Don't be intimidated by this pile of uncommented code. This is just the simplest implementation of star-level controls. In order to make it easier for some readers to edit a widget without querying previous materials.

2. to use the control status, register with the page. Because the registration of the control status cannot be passed between requests during the event sending process, therefore, the custom server control that uses the control status must register each request. Therefore, rewrite the oninit method:

 
Protected override void oninit (eventargs e) {base. oninit (E); page. registerrequirescontrolstate (this );}

3. override the savecontrolstate method. This method saves any server control status changes that occur after the page is sent back to the server. The return value of this method identifies the current status of the server control, therefore, you only need to save the score of the star control to the returned object (to maintain consistency, you still need to call the implementation of the parent class ):

 
Protected override object savecontrolstate () {object [] O = new object [2]; O [0] = base. savecontrolstate (); O [1] = _ score; return O ;}

4. override the loadcontrolstate method. This method restores data from the saved control state. It has a parameter indicating the stored data. This parameter is of the object type, you need to perform the Correct Conversion Based on the type used for saving:

Protected override void loadcontrolstate (Object savedstate) {If (savedstate! = NULL) {object [] O = (object []) savedstate; base. loadcontrolstate (O [0]); _ score = convert. toint32 (O [1]);}

5. after completing the subsequent steps, create An ASPX page declaration on the web site and define the statestar control. Disable the view and add a server button that causes sending back, set the score in the page loading event as in the first step. preview the page again and click the button. The score is displayed correctly:

4. Summary

In this task, we used the control status to save the score of the custom control, so that the custom control can still be used normally when the page view is disabled. In order to use the control status, the page. registerrequirescontrolstate method is called, and the savecontrolstate and loadcontrolstate methods are re-called. Finally, we need to re-state that the control status should only be used to save key numbers.

So far, we have mastered how to develop simple custom controls, the organization, presentation, custom style, control status, and usage features of a star control are also discussed. In the next task, we will develop a complex and challenging control.

ASP. NET Custom ControlsArticle

Preface

Simple star control on the first day

Star controls with custom styles the next day

On the third day, use the star widget in the control status.

Fold panel custom controls on the fourth day

Star controls that can be scored on the fifth day

Star controls that can be bound to data sources on the sixth day

Develop list controls with rich features on the seventh day

Metric days: displays the data binding controls for multiple entry star rating

The ninth day custom gridview

Datalist that implements the paging function on the tenth day

Download all source code

Download this series of articles in PDF

Related Article

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.