ASP.NET – Server Side

We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a control object. All web forms are basically instances of the ASP.NET Page class. The page class has the following extremely useful properties that correspond to intrinsic objects:

  • Session
  • Application
  • Cache
  • Request
  • Response
  • Server
  • User
  • Trace

Server Object


The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform various jobs.

Properties and Methods of the Server object


The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET.

The following table provides a list of the properties:

PropertyDescription
MachineNameName of server computer
ScriptTimeOutGets and sets the request time-out value in seconds.

The following table provides a list of some important methods:

MethodDescription
CreateObject(String)Creates an instance of the COM object identified by its ProgID (Programmatic ID).
CreateObject(Type)Creates an instance of the COM object identified by its Type.
Equals(Object)Determines whether the specified Object is equal to the current Object.
Execute(String)Executes the handler for the specified virtual path in the context of the current request.
Execute(String, Boolean)Executes the handler for the specified virtual path in the context of the current request and specifies whether to clear the QueryString and Form collections.
GetLastErrorReturns the previous exception.
GetTypeGets the Type of the current instance.
HtmlEncodeChanges an ordinary string into a string with legal HTML characters.
HtmlDecodeConverts an Html string into an ordinary string.
ToStringReturns a String that represents the current Object.
Transfer(String)For the current request, terminates execution of the current page and starts execution of a new page by using the specified URL path of the page.
UrlDecodeConverts an URL string into an ordinary string.
UrlEncodeTokenWorks same as UrlEncode, but on a byte array that contains Base64-encoded data.
UrlDecodeTokenWorks same as UrlDecode, but on a byte array that contains Base64-encoded data.
MapPathReturn the physical path that corresponds to a specified virtual file path on the server.
TransferTransfers execution to another web page in the current application.

 

Request Object

The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of the HTTP request that makes the page loading into the browser.

The information presented by this object is wrapped by the higher level abstractions (the web control model). However, this object helps in checking some information such as the client browser and cookies.

Properties and Methods of the Request Object

The following table provides some noteworthy properties of the Request object

PropertyDescription
AcceptTypesGets a string array of client-supported MIME accept types.
ApplicationPathGets the ASP.NET application’s virtual application root path on the server.
BrowserGets or sets information about the requesting client’s browser capabilities.
ContentEncodingGets or sets the character set of the entity-body.
ContentLengthSpecifies the length, in bytes, of content sent by the client.
ContentTypeGets or sets the MIME content type of the incoming request.
CookiesGets a collection of cookies sent by the client.
FilePathGets the virtual path of the current request.
FilesGets the collection of files uploaded by the client, in multipart MIME format.
FormGets a collection of form variables.
HeadersGets a collection of HTTP headers.
HttpMethodGets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.
InputStreamGets the contents of the incoming HTTP entity body.
IsSecureConnectionGets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS).
QueryStringGets the collection of HTTP query string variables.
RawUrlGets the raw URL of the current request.
RequestTypeGets or sets the HTTP data transfer method (GET or POST) used by the client.
ServerVariablesGets a collection of Web server variables.
TotalBytesGets the number of bytes in the current input stream.
UrlGets information about the URL of the current request.
UrlReferrerGets information about the URL of the client’s previous request that is linked to the current URL.
UserAgentGets the raw user agent string of the client browser.
UserHostAddressGets the IP host address of the remote client.
UserHostNameGets the DNS name of the remote client.
UserLanguagesGets a sorted string array of client language preferences.

The following table provides a list of some important methods:

MethodDescription
BinaryReadPerforms a binary read of a specified number of bytes from the current input stream.
Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from object.)
GetTypeGets the Type of the current instance.
MapImageCoordinatesMaps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values.
MapPath(String)Maps the specified virtual path to a physical path.
SaveAsSaves an HTTP request to disk.
ToStringReturns a String that represents the current object.
ValidateInputCauses validation to occur for the collections accessed through the Cookies, Form, and QueryString properties.

Response Object

The Response object represents the server’s response to the client request. It is an instance of the System.Web.HttpResponse class.

In ASP.NET, the response object does not play any vital role in sending HTML text to the client, because the server-side controls have nested, object oriented methods for rendering themselves.

However, the HttpResponse object still provides some important functionalities, like the cookie feature and the Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as outside the application. It requires a round trip.

Properties and Methods of the Response Object

The following table provides some noteworthy properties of the Response object:

PropertyDescription
BufferGets or sets a value indicating whether to buffer the output and send it after the complete response is finished processing.
BufferOutputGets or sets a value indicating whether to buffer the output and send it after the complete page is finished processing.
CharsetGets or sets the HTTP character set of the output stream.
ContentEncodingGets or sets the HTTP character set of the output stream.
ContentTypeGets or sets the HTTP MIME type of the output stream.
CookiesGets the response cookie collection.
ExpiresGets or sets the number of minutes before a page cached on a browser expires.
ExpiresAbsoluteGets or sets the absolute date and time at which to remove cached information from the cache.
HeaderEncodingGets or sets an encoding object that represents the encoding for the current header output stream.
HeadersGets the collection of response headers.
IsClientConnectedGets a value indicating whether the client is still connected to the server.
OutputEnables output of text to the outgoing HTTP response stream.
OutputStreamEnables binary output to the outgoing HTTP content body.
RedirectLocationGets or sets the value of the Http Location header.
StatusSets the status line that is returned to the client.
StatusCodeGets or sets the HTTP status code of the output returned to the client.
StatusDescriptionGets or sets the HTTP status string of the output returned to the client.
SubStatusCodeGets or sets a value qualifying the status code of the response.
SuppressContentGets or sets a value indicating whether to send HTTP content to the client.

The following table provides a list of some important methods:

MethodDescription
AddHeaderAdds an HTTP header to the output stream. AddHeader is provided for compatibility with earlier versions of ASP.
AppendCookieInfrastructure adds an HTTP cookie to the intrinsic cookie collection.
AppendHeaderAdds an HTTP header to the output stream.
AppendToLogAdds custom log information to the InterNET Information Services (IIS) log file.
BinaryWriteWrites a string of binary characters to the HTTP output stream.
ClearContentClears all content output from the buffer stream.
CloseCloses the socket connection to a client.
EndSends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.
Equals(Object)Determines whether the specified object is equal to the current object.
FlushSends all currently buffered output to the client.
GetTypeGets the Type of the current instance.
PicsAppends a HTTP PICS-Label header to the output stream.
Redirect(String)Redirects a request to a new URL and specifies the new URL.
Redirect(String, Boolean)Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.
SetCookieUpdates an existing cookie in the cookie collection.
ToStringReturns a String that represents the current Object.
TransmitFile(String)Writes the specified file directly to an HTTP response output stream, without buffering it in memory.
Write(Char)Writes a character to an HTTP response output stream.
Write(Object)Writes an object to an HTTP response stream.
Write(String)Writes a string to an HTTP response output stream.
WriteFile(String)Writes the contents of the specified file directly to an HTTP response output stream as a file block.
WriteFile(String, Boolean)Writes the contents of the specified file directly to an HTTP response output stream as a memory block.

Example

The following simple example has a text box control where the user can enter name, a button to send the information to the server, and a label control to display the URL of the client computer.

The content file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherits="server_side._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

   <head runat="server">
      <title>Untitled Page</title>
   </head>
   
   <body>
      <form id="form1" runat="server">
         <div>
            
            Enter your name:
            <br />
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
            <br />
            <asp:Label ID="Label1" runat="server"/>

         </div>
      </form>
   </body>
   
</html>

The code behind Button1_Click:

protected void Button1_Click(object sender, EventArgs e) {

   if (!String.IsNullOrEmpty(TextBox1.Text)) {
   
      // Access the HttpServerUtility methods through
      // the intrinsic Server object.
      Label1.Text = "Welcome, " + Server.HtmlEncode(TextBox1.Text) + ". <br/> The url is " + Server.UrlEncode(Request.Url.ToString())
   }
}

Run the page to see the following result:

ASP.NET Server Side

ASP.NET – Server Controls

Controls are small building blocks of the graphical user interface, which include text boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using these tools, the users can enter data, make selections and indicate their preferences.

Controls are also used for structural jobs, like validation, data access, security, creating master pages, and data manipulation.

ASP.NET uses five types of web controls, which are:

  • HTML controls
  • HTML Server controls
  • ASP.NET Server controls
  • ASP.NET Ajax Server controls
  • User controls and custom controls

ASP.NET server controls are the primary controls used in ASP.NET. These controls can be grouped into the following categories:

  • Validation controls – These are used to validate user input and they work by running client-side script.

  • Data source controls – These controls provides data binding to different data sources.

  • Data view controls – These are various lists and tables, which can bind to data from data sources for displaying.

  • Personalization controls – These are used for personalization of a page according to the user preferences, based on user information.

  • Login and security controls – These controls provide user authentication.

  • Master pages – These controls provide consistent layout and interface throughout the application.

  • Navigation controls – These controls help in navigation. For example, menus, tree view etc.

  • Rich controls – These controls implement special features. For example, AdRotator, FileUpload, and Calendar control.

The syntax for using server controls is:

<asp:controlType  ID ="ControlID" runat="server" Property1=value1  [Property2=value2] />

In addition, visual studio has the following features, to help produce in error-free coding:

  • Dragging and dropping of controls in design view
  • IntelliSense feature that displays and auto-completes the properties
  • The properties window to set the property values directly

Properties of the Server Controls

ASP.NET server controls with a visual aspect are derived from the WebControl class and inherit all the properties, events, and methods of this class.

The WebControl class itself and some other server controls that are not visually rendered are derived from the System.Web.UI.Control class. For example, PlaceHolder control or XML control.

ASP.Net server controls inherit all properties, events, and methods of the WebControl and System.Web.UI.Control class.

The following table shows the inherited properties, common to all server controls:

PropertyDescription
AccessKeyPressing this key with the Alt key moves focus to the control.
AttributesIt is the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.
BackColorBackground color.
BindingContainerThe control that contains this control’s data binding.
BorderColorBorder color.
BorderStyleBorder style.
BorderWidthBorder width.
CausesValidationIndicates if it causes validation.
ChildControlCreatedIt indicates whether the server control’s child controls have been created.
ClientIDControl ID for HTML markup.
ContextThe HttpContext object associated with the server control.
ControlsCollection of all controls contained within the control.
ControlStyleThe style of the Web server control.
CssClassCSS class
DataItemContainerGets a reference to the naming container if the naming container implements IDataItemContainer.
DataKeysContainerGets a reference to the naming container if the naming container implements IDataKeysControl.
DesignModeIt indicates whether the control is being used on a design surface.
DisabledCssClassGets or sets the CSS class to apply to the rendered HTML element when the control is disabled.
EnabledIndicates whether the control is grayed out.
EnableThemingIndicates whether theming applies to the control.
EnableViewStateIndicates whether the view state of the control is maintained.
EventsGets a list of event handler delegates for the control.
FontFont.
ForecolorForeground color.
HasAttributesIndicates whether the control has attributes set.
HasChildViewStateIndicates whether the current server control’s child controls have any saved view-state settings.
HeightHeight in pixels or %.
IDIdentifier for the control.
IsChildControlStateClearedIndicates whether controls contained within this control have control state.
IsEnabledGets a value indicating whether the control is enabled.
IsTrackingViewStateIt indicates whether the server control is saving changes to its view state.
IsViewStateEnabledIt indicates whether view state is enabled for this control.
LoadViewStateByIdIt indicates whether the control participates in loading its view state by ID instead of index.
PagePage containing the control.
ParentParent control.
RenderingCompatibilityIt specifies the ASP.NET version that the rendered HTML will be compatible with.
SiteThe container that hosts the current control when rendered on a design surface.
SkinIDGets or sets the skin to apply to the control.
StyleGets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.
TabIndexGets or sets the tab index of the Web server control.
TagKeyGets the HtmlTextWriterTag value that corresponds to this Web server control.
TagNameGets the name of the control tag.
TemplateControlThe template that contains this control.
TemplateSourceDirectoryGets the virtual directory of the page or control containing this control.
ToolTipGets or sets the text displayed when the mouse pointer hovers over the web server control.
UniqueIDUnique identifier.
ViewStateGets a dictionary of state information that saves and restores the view state of a server control across multiple requests for the same page.
ViewStateIgnoreCaseIt indicates whether the StateBag object is case-insensitive.
ViewStateModeGets or sets the view-state mode of this control.
VisibleIt indicates whether a server control is visible.
WidthGets or sets the width of the Web server control.

Methods of the Server Controls

The following table provides the methods of the server controls:

MethodDescription
AddAttributesToRenderAdds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag.
AddedControlCalled after a child control is added to the Controls collection of the control object.
AddParsedSubObjectNotifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control’s control collection.
ApplyStyleSheetSkinApplies the style properties defined in the page style sheet to the control.
ClearCachedClientIDInfrastructure. Sets the cached ClientID value to null.
ClearChildControlStateDeletes the control-state information for the server control’s child controls.
ClearChildStateDeletes the view-state and control-state information for all the server control’s child controls.
ClearChildViewStateDeletes the view-state information for all the server control’s child controls.
CreateChildControlsUsed in creating child controls.
CreateControlCollectionCreates a new ControlCollection object to hold the child controls.
CreateControlStyleCreates the style object that is used to implement all style related properties.
DataBindBinds a data source to the server control and all its child controls.
DataBind(Boolean)Binds a data source to the server control and all its child controls with an option to raise the DataBinding event.
DataBindChildrenBinds a data source to the server control’s child controls.
DisposeEnables a server control to perform final clean up before it is released from memory.
EnsureChildControlsDetermines whether the server control contains child controls. If it does not, it creates child controls.
EnsureIDCreates an identifier for controls that do not have an identifier.
Equals(Object)Determines whether the specified object is equal to the current object.
FinalizeAllows an object to attempt to free resources and perform other cleanup operations before the object is reclaimed by garbage collection.
FindControl(String)Searches the current naming container for a server control with the specified id parameter.
FindControl(String, Int32)Searches the current naming container for a server control with the specified id and an integer.
FocusSets input focus to a control.
GetDesignModeStateGets design-time data for a control.
GetTypeGets the type of the current instance.
GetUniqueIDRelativeToReturns the prefixed portion of the UniqueID property of the specified control.
HasControlsDetermines if the server control contains any child controls.
HasEventsIndicates whether events are registered for the control or any child controls.
IsLiteralContentDetermines if the server control holds only literal content.
LoadControlStateRestores control-state information.
LoadViewStateRestores view-state information.
MapPathSecureRetrieves the physical path that a virtual path, either absolute or relative, maps to.
MemberwiseCloneCreates a shallow copy of the current object.
MergeStyleCopies any nonblank elements of the specified style to the web control, but does not overwrite any existing style elements of the control.
OnBubbleEventDetermines whether the event for the server control is passed up the page’s UI server control hierarchy.
OnDataBindingRaises the data binding event.
OnInitRaises the Init event.
OnLoadRaises the Load event.
OnPreRenderRaises the PreRender event.
OnUnloadRaises the Unload event.
OpenFileGets a Stream used to read a file.
RemovedControlCalled after a child control is removed from the controls collection of the control object.
RenderRenders the control to the specified HTML writer.
RenderBeginTagRenders the HTML opening tag of the control to the specified writer.
RenderChildrenOutputs the contents of a server control’s children to a provided HtmlTextWriter object, which writes the contents to be rendered on the client.
RenderContentsRenders the contents of the control to the specified writer.
RenderControl(HtmlTextWriter)Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.
RenderEndTagRenders the HTML closing tag of the control into the specified writer.
ResolveAdapterGets the control adapter responsible for rendering the specified control.
SaveControlStateSaves any server control state changes that have occurred since the time the page was posted back to the server.
SaveViewStateSaves any state that was modified after the TrackViewState method was invoked.
SetDesignModeStateSets design-time data for a control.
ToStringReturns a string that represents the current object.
TrackViewStateCauses the control to track changes to its view state so that they can be stored in the object’s view state property.

Example

Let us look at a particular server control – a tree view control. A Tree view control comes under navigation controls. Other Navigation controls are: Menu control and SiteMapPath control.

Add a tree view control on the page. Select Edit Nodes… from the tasks. Edit each of the nodes using the Tree view node editor as shown:

ASP.NET Edit Nodes

Once you have created the nodes, it looks like the following in design view:

ASP.NET Edit Nodes2

The AutoFormat… task allows you to format the tree view as shown:

ASP.NET AutoFormat

Add a label control and a text box control on the page and name them lblmessage and txtmessage respectively.

Write a few lines of code to ensure that when a particular node is selected, the label control displays the node text and the text box displays all child nodes under it, if any. The code behind the file should look like this:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;
 
namespace eventdemo {
   public partial class treeviewdemo : System.Web.UI.Page {
   
      protected void Page_Load(object sender, EventArgs e) { 
         txtmessage.Text = " "; 
      }
      
      protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) {
      
         txtmessage.Text = " "; 
         lblmessage.Text = "Selected node changed to: " + TreeView1.SelectedNode.Text;
         TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes;
         
         if(childnodes != null) {
            txtmessage.Text = " ";
            
            foreach (TreeNode t in childnodes) {
               txtmessage.Text += t.Value;
            }
         }
      }
   }
}

Execute the page to see the effects. You will be able to expand and collapse the nodes.

ASP.NET Control Nodes