ASP.NET Autopostback Without Refresh

ASP.NET Autopostback Without Refresh

ASP.NET programming is event-driven. Events on the page, such as pressing a button, are handled on the server. Changes in the text of an edit field, selection of an option in a list, clicking on a checkbox or a switch do not cause immediate sending to the server. This can be achieved by setting the AutoPostBack property for these items.

If AutoPostBack is set for the TextBox control, the TextChanged event will be triggered for it as soon as the field loses focus or the Enter key is pressed. For this property to work, the browser must support ECMAScript (a JavaScript standard adopted by the European Computer Manufacturers Association).

Data sources for controls can be data tables. Let’s look at the example included in Visual Studio – CarSelectorSample. It takes place in an electronic car store. There are different brands of cars, and there are several models for each brand. When you select a car brand in the first list, the corresponding models are automatically loaded into the second list.

BrandBuickChevroletPontiacToyotaMileageFeatures
      Power seat
BuickCenturyImpalaGrand AmAvalon0-10000Leather seat
ChevroletLeSabreMalibuGrand PrixCamry10000-20000Sun roof
PontiacPark AvenueMetroMontanaCamry Solara20000-30000CD player
ToyotaRegalPrizmSunfireCelica30000 and moreABS

All data used on this page are collected in a table. There is a class DataTable for storing such a table. The table consists of columns – DataColumn and rows – DataRow. The DataView class allows you to create different views of the table data. The first column serves as a source of data for the list of brands. Depending on the selected model, one of 2 to 5 columns is loaded into the model list.

First, the table is created.

Cars = new DataTable();
Cars.Columns.Add(new DataColumn("Brand", typeof(string)));

Here one of the DataColumn constructors is called. The first argument is the name of the column, the second is the type.

CarRow = Cars.NewRow();

A new table row is created. The table cell is specified using the row index.

CarRow[6]="Power seat";

And the row is added to the table.

Cars.Rows.Add(CarRow);

The brand drop-down list has the AutoPostBack property set. This means that the page is automatically served to the server when the selected item in this list changes.

In the new item selection handler, we first find out which item is selected.

string selected = DropDownList1.SelectedItem.Value;

The switch statement switches the second list to one of the table columns by setting the DataTextField and DataValueField properties, where DataTextField is the text displayed in the list and DataValueField is the selected value. In this case, as is often the case, they are the same.

Binding to data

Some controls: lists, tables, and others have a DataSource property that is responsible for data binding. The type of this property is object, which means it can be of any type, but this type must implement the IEnumerable interface. Often the values of this property are assigned to collections. In that case, there is no need to add values manually. The DataSource property can be bound to collections that support the IEnumerable, ICollection or IListSource interfaces. The data source can also be XML files, databases. By calling the DataBind method, the data is bound to the control. The Page.DataBind method binds data for all elements on the page.

The drop-down list below helps you choose a continent to travel to. The data source is a dynamic array called ArrayList. Use it if you have a lot of insertions and deletions in your program.

void Page_Load() 
      { 
          ArrayList ContinentArrayList = new ArrayList(); 
          ContinentArrayList.Add("Worldwide"); 
          ContinentArrayList.Add("America"); 
          ContinentArrayList.Add("Africa"); 
          ContinentArrayList.Insert(1, "Asia-Pacific"); 
          ContinentDropDownList.DataSource = ContinentArrayList; 
          ContinentDropDownList.DataBind(); 
      } //End Page_Load() 
  .... 
  <asp:DropDownList id="ContinentDropDownList" runat="server" />

You can use a Hashtable as a data source. Hash tables are data structures that were invented long ago (see Volume 3 of The Art of Programming by D. Knuth), but for a long time programmers had to implement them manually. In php the usual array is a hash table. The STL library for C++ also has a type map, which stores data in this way. Hash tables allow you to very quickly find the value of the key. The index in a collection is calculated as a simple hash function of the key. In C#, keys are used as indexers. Use Hashtable if the program is searched frequently. Insertion and deletion are slow in it. Keys can be of any type. A virtual method GetHashCode is defined in the Object class, and it is used in the Hashtable.

  <%@ Page Language="C#" %> 
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  <script runat="server"> 
  void calSelectChange(Object sender, EventArgs e) 
  { 
       lblShow.Visible = false; 
       Hashtable hshDays = new Hashtable(); 
       hshDays[Convert.ToDateTime("2/6/2006")] = "Algebra exam"; 
       hshDays[Convert.ToDateTime("3/6/2006")] = "С# exam"; 
       hshDays[Convert.ToDateTime("4/6/2006")] = "Getting Started with ASP.NET"; 
       hshDays[Convert.ToDateTime("1/6/2006")] = "Children's Day"; 
       DateTime datDateIn; 
       datDateIn = calDays.SelectedDate; 
       if (Page.IsPostBack) 
       { 
           lblShow.Text = "On that day, the appointment is: "; 
           lblShow.Text += hshDays[datDateIn]; 
           if (hshDays[datDateIn] == null) 
               lblShow.Text = "Nothing is assigned."; 
           lblShow.Visible = true; 
       } 
  } 
  </script> 
  <html xmlns="http://www.w3.org/1999/xhtml" > 
  <head runat="server"> 
      <title>Let's try a hash table</title> 
  </head> 
  <body> 
      <form id="form1" runat="server"> 
      <div> 
      <h3>Diary 
  </h3> 
  Enter the date between 1/6/2006 and 30/6/2006 
  <asp:Calendar id="calDays" runat="server"  
  OnSelectionChanged="calSelectChange" 
  VisibleDate="06/06/2006" 
  ></asp:Calendar> 
  <br /> 
  <br /> 
  <asp:Label id="lblShow" runat="server"></asp:Label> 
      </div> 
      </form> 
  </body> 
  </html> 
  

Here the hash table key is the date. Convert.ToDateTime converts the string to a date type. VisibleDate ensures that the calendar is June 2006. If there are no values for the key in the table, the indexer simply returns null. Values can be entered in any order.

I would like to add a new feature to the page to enter new entries. You can introduce new controls – input line and button to feed the data. When the button is clicked, a new value will be added to the hash table.

void Button1_Click(object sender, EventArgs e) 
      { 
          hshDays[calDays.SelectedDate]=TextBox1.Text; 
      }

This page does not work. The point is that the page is reloaded when the date changes. The hash table is re-created, and the values entered in it are lost. How to solve this problem? Let’s make the hash table a static variable.

static Hashtable hshDays; 
  void calSelectChange(Object sender, EventArgs e) 
  { 
      DateTime datDateIn = calDays.SelectedDate; 
      lblShow.Text = "On that day, the appointment is: "; 
      lblShow.Text += hshDays[datDateIn]; 
      if (hshDays[datDateIn] == "") 
          lblShow.Text = "Nothing is assigned."; 
  } 
  void Page_Init() 
  { 
      if (!Page.IsPostBack) 
      { 
          hshDays=new Hashtable(); 
          hshDays[Convert.ToDateTime("2/6/2006")] = "Algebra exam"; 
       hshDays[Convert.ToDateTime("3/6/2006")] = "С# exam"; 
       hshDays[Convert.ToDateTime("4/6/2006")] = "Getting Started with ASP.NET"; 
       hshDays[Convert.ToDateTime("1/6/2006")] = "Children's Day"; 
          Session["Diary"]= hshDays; 
       } 
  } 
  void Record(Object sender, EventArgs e) 
  { 
      DateTime datDateIn = calDays.SelectedDate; 
      hshDays[datDateIn]= Entrance.Text; 
      lblShow.Text = hshDays[datDateIn].ToString(); 
  } 
  
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
Read More

App Model ASP.NET

Difference between applications ASP.NET and feature-rich client applications, which makes a lot of sense when analyzing the execution…
Read More

Web projects

So far, we’ve only covered how you can create websites without any project files. The advantage of project-free development…