Saving Bandwidth Using UpdatePanel Triggers

Most of the web applications that we build today are Ajaxified. An Ajaxed web page results in better user experience with partial-page updates that refreshes only the parts of the web page. Ajax was invented by Microsoft when they included XMLHttpRequest object in Internet Explorer 4, which is now available in most of the web browsers. The XMLHttpRequest object allowed developers to make Http GET and POST requests without submitting the whole web page. However to build an Ajax-enabled web site, developer needed to have in-depth knowledge of Javascript. As Ajax matured a number of frameworks have been developed that make Ajaxifying a web page very easy e.g., JQuery, Prototype, MooTools, etc. Microsoft has also provided one such tool for ASP.net developers, which is known as Microsoft ASP.Net Ajax.

Using Microsoft ASP.Net Ajax we can perform the partial-page updates without writing any code. Any web page that contains a ScriptManager and one or more UpdatePanel control can do asynchronous postbacks. UpdatePanel acts as a container control and when a control within the same triggers an asynchronous postback only the contents within the UpdatePanel are refreshed, which avoids the flicker. Asynchronous postbacks in ASP.Net Ajax behave like the regular postbacks, however the updates are limited to the parts of the web page that are enclosed in the UpdatePanel.

By default whenever any asynchronous postback is triggered within the page all the UpdatePanels are refreshed. This doesn’t seem to be a problem at first but this is quite expensive in terms of server capacity. When an asynchronous postback is done, to maintain the state of all the controls the entire view state is submitted to the server. After server executes the page the data of entire view state is processed and passed back to the UpdatePanel. In most cases the view state data of all the UpdatePanels controls does not change with every asynchronous postback. If we can avoid moving the view state data of all the UpdatePanels from server to client, we will save significant amounts of bandwidth. This can be achieved using UpdatePanel Triggers.

Let’s create a sample ASP.net application to illustrate the use of UpdatePanel Triggers to save the bandwidth.

Open the SQL Server Management Studio and create a new Contacts database. Add the Contact and Address table to the database having the below structure.

Contact Table

Address Table

Address_ID field in the Contact table is a Foreign Key that references the ID field of the Address table. Now add some sample data to these two tables and close the SQL Server Management Studio.

Open the Visual Studio 2008 and create a new HTTP type web site, name it as ContactManager.

Add the below controls to the Default.aspx web form that is added by default to the web site.

Control ID
ScriptManager ContactsScriptManager
Textbox FirstNameTextBox
TextBox LastNameTextBox
Button FindButton
UpdatePanel ContactUpdatePanel
GridView ContactsGridView
UpdatePanel AddressUpdatePanel
DetailsView AddressDetailsView

ContactsGridView and AddressDetailsView should be placed within the ContactUpdatePanel and AddressUpdatePanel respectively. Add columns to the ContactsGridView and AddressDetailsView using the Smart Tags; columns should correspond to the columns in the Contact and Address tables that we created above. Now the web form should look like below in the design view.

Now open the web.config file and add the below connection string.

<connectionStrings>
   <add name="ContactDB"
        connectionString="Data Source=.;Initial Catalog=Contacts;Integrated Security=SSPI;"
        providerName="System.Data.SqlClient"/>
</connectionStrings>

Now add a class file to the project and name it as DataBinder.cs. We will use this class file to bind the UI to the database. We can use the built-in controls to do that like SQLDataSource but it is not recommended to hide all the queries in a control in professional/enterprise applications. In DataBinder.cs file create below two classes.

Contact Class

public class Contact
{
   private int _ID;

   public int ID
   {
      get { return _ID; }
      set { _ID = value; }
   }

   private string _FirstName;

   public string FirstName
   {
      get { return _FirstName; }
      set { _FirstName = value; }
   }

   private string _LastName;

   public string LastName
   {
      get { return _LastName; }
      set { _LastName = value; }
   }

   private string _Title;

   public string Title
   {
      get { return _Title; }
      set { _Title = value; }
   }

   private string _Company;

   public string Company
   {
      get { return _Company; }
      set { _Company = value; }
   }

   private string _Department;

   public string Department
   {
      get { return _Department; }
      set { _Department = value; }
   }

   private string _Mobile;

   public string Mobile
   {
      get { return _Mobile; }
      set { _Mobile = value; }
   }

   private string _Phone;

   public string Phone
   {
      get { return _Phone; }
      set { _Phone = value; }
   }

   private string _Email;

   public string Email
   {
      get { return _Email; }
      set { _Email = value; }
   }

   private int _Address_ID;

   public int Address_ID
   {
      get { return _Address_ID; }
      set { _Address_ID = value; }
   }
}

DataBinder Class

public class DataBinder
{
   DbProviderFactory DBFactory;
   DbConnection ConObject;

   public DataBinder()
   {
      DBFactory =
         DbProviderFactories.GetFactory("System.Data.SqlClient");
      ConObject = DBFactory.CreateConnection();
      ConObject.ConnectionString =
         ConfigurationManager.ConnectionStrings["ContactDB"].
         ConnectionString;
      ConObject.Open();
   }

   public DataView GetContacts(string firstname, string lastname)
   {
      DataView returnObj;
      using (DbCommand com = DBFactory.CreateCommand())
      {
         com.CommandText = "SELECT * FROM [Contact]
            WHERE UPPER([FirstName]) LIKE @FirstName
            AND UPPER([LastName]) LIKE @LastName";
         com.Connection = ConObject;

         DbParameter firstnameParameter = DBFactory.CreateParameter();
         firstnameParameter.ParameterName = "@FirstName";
         firstnameParameter.Value = "%" + firstname.ToUpper() + "%";
         com.Parameters.Add(firstnameParameter);

         DbParameter lastnameParameter = DBFactory.CreateParameter();
         lastnameParameter.ParameterName = "@LastName";
         lastnameParameter.Value = "%" + lastname.ToUpper() + "%";
         com.Parameters.Add(lastnameParameter);

         DataTable tempTable = new DataTable();
         tempTable.Load(com.ExecuteReader());
         returnObj = tempTable.DefaultView;
      }
      return returnObj;
   }

   public DataView GetAddress(int id)
   {
      DataView returnObj;
      using (DbCommand com = DBFactory.CreateCommand())
      {
         com.CommandText = "SELECT * FROM [Address]
            WHERE [ID] = @ID";
         com.Connection = ConObject;

         style='color:#2B91AF'>DbParameter idParameter =
            DBFactory.CreateParameter();
         idParameter.ParameterName = "@ID";
         idParameter.DbType = DbType.Int32;
         idParameter.Value = id;
         Parameters.Add(idParameter);

         DataTable tempTable = new DataTable();
         tempTable.Load(com.ExecuteReader());
         returnObj = tempTable.DefaultView;
      }
      return returnObj;
   }

   public int UpdateContact(Contact modifiedContact)
   {
      int returnVal;
      using (DbCommand com = DBFactory.CreateCommand())
      {
         com.CommandText = "UPDATE [Contact] SET [FirstName] =
            @FirstName, [LastName] = @LastName, " +
            "[Title] = @Title, [Company] =
               @Company, [Department] = @Department, " +
            "[Mobile] = @Mobile, [Phone] = @Phone, [Email] =
               @Email, [Address_ID] = @Address_ID " +
            "WHERE [ID] = @ID";
         com.Connection = ConObject;

         DbParameter firstnameParameter = DBFactory.CreateParameter();
         firstnameParameter.ParameterName = "@FirstName";
         firstnameParameter.Value = modifiedContact.FirstName;
         com.Parameters.Add(firstnameParameter);

         DbParameter lastnameParameter = DBFactory.CreateParameter();
         lastnameParameter.ParameterName = "@LastName";
         lastnameParameter.Value = modifiedContact.LastName;
         com.Parameters.Add(lastnameParameter);

         DbParameter titleParameter = DBFactory.CreateParameter();
         titleParameter.ParameterName = "@Title";
         titleParameter.Value = modifiedContact.Title;
         com.Parameters.Add(titleParameter);

         DbParameter companyParameter = DBFactory.CreateParameter();
         companyParameter.ParameterName = "@Company";
         companyParameter.Value = modifiedContact.Company;
         com.Parameters.Add(companyParameter);

         DbParameter departmentParameter = DBFactory.CreateParameter();
         departmentParameter.ParameterName = "@Department";
         departmentParameter.Value = modifiedContact.Department;
         com.Parameters.Add(departmentParameter);

         DbParameter mobileParameter = DBFactory.CreateParameter();
         mobileParameter.ParameterName = "@Mobile";
         mobileParameter.Value = modifiedContact.Mobile;
         com.Parameters.Add(mobileParameter);

         DbParameter phoneParameter = DBFactory.CreateParameter();
         phoneParameter.ParameterName = "@Phone";
         phoneParameter.Value = modifiedContact.Phone;
         com.Parameters.Add(phoneParameter);

         DbParameter emailParameter = DBFactory.CreateParameter();
         emailParameter.ParameterName = "@Email";
         emailParameter.Value = modifiedContact.Email;
         com.Parameters.Add(emailParameter);

         DbParameter addressIDParameter = DBFactory.CreateParameter();
         addressIDParameter.ParameterName = "@Address_ID";
         addressIDParameter.DbType = DbType.Int32;
         addressIDParameter.Value = modifiedContact.Address_ID;
         com.Parameters.Add(addressIDParameter);

         DbParameter idParameter = DBFactory.CreateParameter();
         idParameter.ParameterName = "@ID";
         idParameter.DbType = DbType.Int32;
         idParameter.Value = modifiedContact.ID;
         com.Parameters.Add(idParameter);

         returnVal = com.ExecuteNonQuery();
      }
      return returnVal;
   }
}

More by Author

Must Read