HTML Controls are collection of the server side controls that give the server side representation of the client side HTML elements. We can create a server side object by giving any client side HTML element with the attribute of runat=”server” and giving it an identifier. This is a very convenient way of manipulating server side elements without messing up the markup. It is useful at places where you have already existing HTML elements in you code and you do not want to completely replace them with the server side web controls then we can set up the marking for some of the controls to runat server.
Let’s have a look at this in action. Let’s open the exiting folder that contains the files HelloWorldCodeBehind.aspx and HelloWorldCodeBehind.aspx.cs as a website in Visual Studio
It would look something like below.
What we will see here is how to use an HTML server side control to get rid of the inline markup of GetType. The first way we can do this is go the h3 element and give it the runat server attribute and an id. Also we will remove the GetType call and replace it with xxxxxxxx to indicate that this value will be updated.
Now let’s go to the code behind. We will tap the load event and do what we were doing in the aspx. When we add the attribute runat server then we get access to that type in our server side code.
Another category of the server side controls is WebControls and its present in the System.Web.UI.WebControls namespace. These are generally used over there HTML counter parts as these are listed as the standard controls in the toolbox. They are more convenient to work with because they have more consistent property names. So once you know how to use one control you can easily use the other which is not the same in the case of HTML controls. Many of these Web Controls are replacement of the HTML controls and other are more complex.
Let’s see these web controls in code. So we have already used BulletedList which is a webcontrol that renders as an unordered list. So let’s remove the Response.Write and replace it with a label.
Now we will add the logic to display the total number of items in the label inside the Load Event in the server side code.
Let’s add a calendar and display it on the page.
When we view the source of the displayed aspx page we will not see a control but a table with all the elements defined in it.
Control State Management
One of the most important things in Control State Management in ASP.NET is that they maintain their states even during the post backs. So sequence is as below:
- The initial get request to a page creates the server side controls with their default values specified on the initial form.
- Then if the user clicks on an element that generates a post request onto the same page then this would generate the POST message that would be handled in the server. Then when the server creates the page then the page creates the server side controls with the values in the POST body of the request that came back.
- So the changes that are made by the client in the controls will be reflected in the server side controls and consequently the response for page render.
The flow of the Web Form Client interaction is shown in the image below.
Let’s see that in action. Let’s create a new page named State.aspx and add the following code to it.
When we run this page we can see state retention in action.
There are several implications of State Retention as well.
- There is no need to re initialize state in controls when we are processing post back requests.
- Can’t do cross page posting by default.
- Controls that are not intrinsically included in a POST back will not retain their state by default and we will have to request their state propagation via hidden fields.
Let’s see this in action by optimizing our Load event code. We will check for the IsPostBack property of the page to determine whether this load is a post back or not. If it is not then only we assign states to the controls otherwise the state will be retained.
The model of state retention for server side controls is pretty simple when we look at the input controls that are sent back as part of the post back. Now we need to see how the controls that do not contribute to the POST body will maintain their states. These elements includes div, span, li, p, table, etc. The answer is ViewState. ViewState is the additional hidden input element which is generated when each page is rendered and it is used by controls to insert additional state during post back.
The best way to see this is in code. Let’s create another Form named ViewState and add the following code to it.
So whenever we click on the button a post back happens but the state of the label is still persisting its state.
ViewState is persisted as a serialized tuple-based data structre and encoded as a base64 string. So we can use any base64 decoder to decode the ViewState. We can download a ViewState Decoderfrom http://tinyurl.com/4dn377. It would look something like below.
ViewState is a perfectly useful way to propagate requests while dealing with small controls that have fairly less ViewState associated with them but large amount of ViewState on controls like databound controls we must turn it off. There are two way in which we can disable the ViewSate.
- Set EnableViewState=”False” in the page directive. This will disable the ViewState for the entire page.
- Set EnableViewState=”False” on the individual controls. You can identify thecontrols that does not require ViewSate and set this attribute and we should do this on the controls that have a significant ViewState usage.
This will reduce the amount of data in the request that goes back and forth.
Change Notification Events
In the previous section we have seen when and where to disable the ViewState. In this section we will see where we should not disable ViewState.
- Do not disable ViewState on Server-Side controls that issue change notifications events based on ViewState.
- Because the Prior Value is stored in the ViewState to keep track of the changes.
- During subsequent POST requests the current and the cached values are compared and if they are different then a change notification is issued.
EventTarget and EventArgument Fields
There is another method to find out which server side control actually initiated the server side request and this has an EventTarget field and an EventArgument field. Some input elements like Button, imagebutton, etc already send data in the POST body that can help us identify the sender. But there are some controls that do not use standard postback mechanisms. For example the change notification in thelinkbutton, drop down list when autopostback=”true”. This does not have any data included in the POST that will help us identify that it is the control that initiated the postback. That is why there are these 2 other fields which helps us identify as to which control issued the postback. So the EventTarget Hidden field stores the control id that issued the event and the EventArgument Hidden Field will store any parameters sent for the event.
ControlState is a feature which was added with release 2.0 of ASP.NET. The idea behind ControlState is to give the developer another repository for saving the state apart from the ViewState that cannot be disabled. This was to fix the issue that was faced in the previous version when the ViewState for certain controls like GridView, etc was disabled then the control did not work properly. So now the user has the option to distinguish the behaviour state by placing it into the controlstate and by placing simple data into viewstate. ControlState is not a separate hidden field but it is an additional collection of state data appended to the end of ViewState. So we can now turn off the view state for the controls without any issues. So all of the newer data-bound controls in ASP.NET makes use of the Control State.
Explicit Use of ViewState
ViewState can also be used as the means to store client-specific state which will retained across the POST requests to the same page. But we need to make sure that the types are serializable. These are directly accessible from the Page.ViewState property on the page and it returns the collection of the ViewState properties.
So let’s see how we can make exclusive use of the ViewState property. Add a new WebForm to our existing website and add a listbox in the aspx file. Also lets add the label to the aspx.
Now let’s add a handler for selectionchanged event of the ListBox. We will add the logic that whenever the user clicks on the listbx we will update the label by storing the count in the ViewState.
The code for this Post can be found here.
Any questions, comments and feedback are most welcome.