Home
Home Page
And again about functional programming on Python
Where the Python has come crawling?
Practical application OOP in PHP5
Functional programming in language Python
Approaches of language Python - an amusing example of optimization
Use ext/mysqli: Part I - the Review and the prepared expressions
How to receive the maximal result from registration in catalogues
XML-RPC In language Python
The API-specification of databases of language Python, version 2.0
Programming of the Web-client in language Python
Useful advice for job with XML
Future Web - behind semantics
Whether it is necessary to cancel spaces of names XML?
Use AJAX in ASP.NET
ASP .NET 2.0: Reference pages
Patterns of registration
What is ASP.NET. Installation and the test project.
Anatomy ASP.NET. ASP.NET in operation.
Server elements of management Continuation.
Links
 
topic


Use AJAX in ASP.NET

History of development of web-applications


Considering{Examining} this or that new technology first of all it is necessary to understand for what this technology what exactly is necessary also she allows (or facilitates) to do{make}, that do not allow to do{make} other technologies. More evidently to understand, what preconditions were to occurrence AJAX, it is possible to consider process of evolutionary development of web-sites.


At the dawn of development the Internet sites represented a set of simple static pages - the user requested a resource of the server and the server returned static page. This page represented idle time HTML the text and was stored{kept} as a text file on the server. The given page was delivered the user as is and besides had no any client scripts.


CGI


The first attempt to make page more dynamical was Common Gateway Interface (CGI.) CGI allowed the developer to create executed programs which generated page that allowed to accept parameters from the user. In view of these parameters it was possible to generate unique page. By and large, the given approach is used and now in the same ASP.NET, PHP, etc.


JavaScript


Generation of pages on the server party{side} it is certainly good, but it compelled at everyone, even the most insignificant action of the user, to interpellate to the server with an overload of all page. To not overload all page in cases when participation of the server is absolutely not necessary, client scripts began to be used.


Applets and Flash


In case the search to the server nevertheless is necessary to not do without also one client scripts - developers in web-pages began to use so-called applets and also flash.


Applets for the first time have been used in 1995 when Sun has presented the world on a general review the new platform with a modern language - JAVA. As a matter of fact applets represented the programs written on JAVA and which could be started in a browser as separate applications. That this program written in unknown language for browser JAVA, could be started inside a browser, it was necessary to establish JVM (Java Virtual Machine) - environment{Wednesday} for performance of programs JAVA. And though the given approach sounds is very tempting - he had set of lacks, first of all it is problems of safety (not each user, travelling on the Internet, will allow to start on the computer of the program of not clear origin) and necessity gromozkoj VM. In spite of the fact that besides dialogue with the server applets and flesh also allowed to realize the opportunities inaccessible JavaScript (we shall say, to the schedule) - those complexities did not give higher requirements to applets to get accustomed so finally to solve problems with searches to the server.


DHTML


Dynamic HTML has united in itself HTML, cascade tables of styles (CSS) and JavaScript. Also to all this set it was added DOM - objective model of a browser. All this mix allowed (and allows) to create successfully very beautiful, convenient and functional pages "hurriedly". But besides, in case it is necessary to execute search to the server - it is necessary to overload the document.


AJAX


The decision of this problem has come with the advent of new technology which in 2004 has been named AJAX (Asynchronous JavaScript + XML). The given technology is constructed on a principle of performance of search to the server with use JavaScript and to reception of result besides, with help JavaScript that allows to avoid an overload of page and therefore has some conclusive advantages:


1. On the server all elements of page (more precisely not their values), but only those minimal data which are necessary for performance of this or that search are sent not and in the answer all page is accepted not, but only the necessary data, that allows to reduce the traffic in tens (and sometimes and in hundreds) time.

2. There is no overload of page in a browser and at the user the impression is created, that all occurs on his{its} computer.


About this technology also there will be further a speech.

Objective model of a browser.


If you ask me on what the principle of job of technology AJAX I probably shall answer you is based: « due to objective model of a browser ». What it for such objective model of a browser (DOM)?


Document Object Model (DOM) is the specification standardized W3C by committee which is krossplatformennoj and describes calls and the descriptions, concerning to actions with the document, his{its} structure, HTML, XML and styles. As follows from the name, a basis of specification DOM are objects.


Object XMLHttpRequest


This object has appeared for the first time in Internet Explorer 5.0 and has been realized as ActiveX a component. It is important to notice, that this object is not standard W3C though much of his{its} functionality is described in the specification « The DOM Level 3 Load and Save Specification ». For this reason his{its} behaviour can differ a little in various browsers. But in all browsers he carries out the same functionality - he is able to send searches to the server and to receive from him{it} answers. As it was already spoken above, the given object is not standardized also his{its} creation instance can differ in various versions, therefore for his{its} "reliable" creation better use a code which unites in itself creation instance in several browsers is similar to a code below:



var xmlHttp;

  function createXMLHttpRequest () 

  {

  if (window. ActiveXObject) 

  {

  xmlHttp = new ActiveXObject (" Microsoft. XMLHTTP ");

}

  else if (window. XMLHttpRequest) 

  {

  xmlHttp = new XMLHttpRequest ();

}

}


XMLHttpRequest has a number{line} "standard" (standard so-called since as it was written above, the given object is not standardized for all browsers) properties and methods which allow the given object to send search, to check a status of search and to receive result of performance of search from the removed server. We shall consider these properties and methods in the following two tables.


In table 1 "standard" properties XMLHttpRequest are submitted


Method



The description


abort ()



Interrupts the current search


getAllResponseHeaders ()



Returns all headings Response as key / value


getResponseHeader (header)



Returns value of the certain heading


open (method, url, asynch, username, password)



Establishes a status of search to the server. The first parameter specifies a method of search - PUT, GET, POST, the second - url search, the third (unessential) - type of search (synchronous or asynchronous), the fourth and the fifth (also unessential) - for the protected pages


send (content)



Sends search to the server


setRequestHeader (header, value)



Establishes value of the certain heading. Before a call of this method it is necessary to call a method open


Also XMLHttpRequest contains a number{line} of properties which are submitted below:


Property



The description


onreadystatechange



Obrabotchik event which arises at each change of a status of search


readyState



Status of search. The following values are accessible: 0 - search neinicializirovan, 1 - loading, 2 - loading is ended, 3 - interactive, 4 - complete


responseText



The answer from the server as a line


responseXML



The answer from the server in XML. This object can be processed and checked up as DOM


status



Code of status HTML. (for example 200 - OK)


statusText



The name of a code of status HTML


Fluently having appeared these methods, it is simple to understand, what methods need to be called, that with help JavaScript to receive any from the server.


First of all we shall write a server part which will return a simple line. For this purpose (that there were no "extraneous" data like tegov opening of closing html) it will be most rational to create hanlder. We open the web-project in Visual Studio 2005 and we create a file such as Handler. Contents will be approximately following:



<% WebHandler Language = " C * " Class = "MyHandler" %>

  using System;

  using System. Web;

  public class MyHandler: IHttpHandler {

      public void ProcessRequest (HttpContext context) {

          context. Response. ContentType = "text/plain";

          context. Response. Write (" Hello World ");

}

      public bool IsReusable {

          get {

              return false;

}

}

}


I.e. at search of the given page this hanlder returns text/plain the document with a unique line ” Hello World “. Us such handler arranges as well as possible.


Now we shall create usual HTML - page which will and carry out search, using XMLHttpRequest.



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

  <head>

      <title> Simple XMLHttpRequest page </title>

      <script type = "text/javascript">

          var xmlHttp;

          function createXMLHttpRequest () 

          {

              if (window. ActiveXObject) 

              {

                  xmlHttp = new ActiveXObject (" Microsoft. XMLHTTP ");

}

              else if (window. XMLHttpRequest) 

              {

                  xmlHttp = new XMLHttpRequest ();

}

}

          function startRequest () 

          {

              createXMLHttpRequest ();

              xmlHttp.onreadystatechange = handleStateChange;

              xmlHttp.open ("GET", "MyHandler.ashx", true);

              xmlHttp.send (null);

}

          function handleStateChange () 

          {

              if (xmlHttp.readyState == 4) 

              {

                  if (xmlHttp.status == 200) 

                  {

                      alert (" Response: " + xmlHttp.responseText);

}

}

}

      </script>    

  </head>

  <body>

      <input type = "button" value = " Start Asynchronous Request "

          onclick = " startRequest (); "/>

  </body>

  </html>


The given code is rather simple. By pressing the button ” Start Asynchronous Request “ client function startRequest is caused, which in turn all over again causes the function considered by us earlier createXMLHttpRequest for creation of object XMLHttpRequest, then clings obrabotchik (client function handleStateChange) on event ReadyStateChange for this object, opens and sends search. If the required page is accessible also the data have been received, status changes the status on 200. Therefore in function handleStateChange we check value of this property. At the necessary value we with the help alert deduce{remove} the received value. We taste as it works:



In the given simple code all as a matter of fact is incorporated fukcional`nost` AJAX - data acquisition from the server without an overload of page. It is enough understanding of this mechanism to understand essence AJAX, and also successfully to use it{him} in the applications. Further only a trick and further we shall consider realization of all it, but with use ASP.NET J

Use AJAX in ASP.NET

Callbacks of page.


Callbacks are a special kind of return of the form, i.e. the page passes the cycle of events, but the given forms come back to the client prior to the beginning of process of rendering of the form, i.e. before copying. As well as in any AJAX execution{performance} the search begins on the client party{side} as a result of occurrence of any event, thus the client built - in function under name WebForm_DoCallback is started.



WebForm_DoCallback (pageID, argument, returnCallback, context, errorCallback, useAsync);


Where:


pageID - ID pages which carries out a call,


argument - the line argument transmitted to the server,


returnCallback - client function or a client script which should be executed after the server party{side} will return management


context - the data which are passed returnCallback.


errorCallback - client function or the client script which is carried out at occurrence of mistakes


useAsync - establishes, whether there will be a search synchronous or asynchronous.


- the server page should know the following stage, that she should support callbacks (i.e. first of all to return the pages given prior to the beginning of rendering). For this purpose this page should realize interface System. Web. UI.IcallbackEventHandler.


The given interface contains 2 methods:




public interface ICallbackEventHandler

  { 

  string GetCallbackResult ();

  void RaiseCallbackEvent (string eventArgument); 

}


Performance of callback on the server party{side} will consist of 2 stages: preparation and returning of result. Method RaiseCallbackEvent is caused by the first and intended for preparation of the removed performance of a code. Method GetCallbackResult is carried out later when the result is available to sending. The given division has been entered only in release versions .NET 2.0, in the previous versions these 2 methods have been incorporated into one (it has been made in view of asynchronous job). Method GetCallbackResult returns string, therefore the returned data should be serializirovany that or other method at line, and on the client on the contrary, deserializirovany.


At search of page from a client script all over again it is carried out Init then a standard cycle of events of loading of page before event Load, in Load property IsCallback is established in true, on end Load methods of interface ICallbackEventHandler then as performance was already spoken above interrupts are carried out, not passing in a stage of rendering. First of all it speaks that there is no stage of preservation ViewState so to try to save something in ViewState in the standard way is useless (it and is understandable, since ViewState pages is not updated). The manager of callbacks operates process of interaction between page and the server so-called. The manager of callbacks has in itself library of client scripts. These client scripts form and send search, receive and assort the answer from the server, etc. Having seen View Source any of pages can see lines like



<script src = "/WebResource.axd? d=VWLFgbEM584QkLzy5eDwGw2*amp; t=632964616335443742 " type = "text/javascript"> </script>


Having downloaded a file which returns given obrabotchik WebResource.axd with the specified parameters, it is possible to go deep into studying client scripts which are responsible for mentioned above actions J


Method GetCallbackEventReference


The spelling of client method WebForm_DoCallback is not something complex{difficult}, however is connected to some difficulties in case of dynamic generating or transfer of parameters. For this purpose the special method is entered into class Page. ClientScript (System. Web. UI.ClientScriptManager) - GetCallbackEventReference which receives a number{line} of parameters and, is similar for example to method GetPostBackEventReference, generates a corresponding client code. I would not say, that this method very graceful, is especial when it is necessary to pass parameters in klienskij a script (especially presence of unary and double inverted commas in kontatenirujuhhejsja to a line spoils all picture), but all is more convenient, than to a forehead to write WebForm_DoCallback.


The following prototype has the given method:



public string GetCallbackEventReference (

  Control target,

  string argument,

  string clientCallback,

  string context,

  string clientErrorCallback,

  bool useAsync)


Where:


target - page or WebControl which will process callback. Accordingly, this page or kontrol should realize interface ICallbackEventHandler, exception differently will be thrown:


System. InvalidOperationException: The target ' __ Page ' for the callback could not be found or did not implement ICallbackEventHandler.



Generuet the first parameter of function WebForm_DoCallback


argument - the argument transmitted to client function or a script. Corresponds{meets} to the second parameter of function WebForm_DoCallback.


returnCallback - client function or a client script which should be executed after the server party{side} will return management (3-rd parameter WebForm_DoCallback)


context - the data which are passed client returnCallback (4-th parameter WebForm_DoCallback).


errorCallback - client function or the client script which is carried out at occurrence of mistakes (5-th parameter WebForm_DoCallback)


useAsync - establishes, whether there will be a search synchronous or asynchronous (6-th parameter WebForm_DoCallback).


Now we can create our the first aspx page with use ajax. We admit{allow}, rather often problem{task} - is 2 dropping out lists - in one of them the data of higher level, rather than in the second. I.e. at a choice of value in the first list - the second list is overloaded depending on the chosen value in the first. For example - the first SELECT contains the list of manufacturers of the machines, the second - models of machines which the chosen manufacturer issues. For the decision of this problem{task} it is possible to load certainly all data in javascript, and then a script perebindivat` the second select. In our case it basically would approach, but there are some minuses - the first it that the data can be much (we admit{allow}, 100 manufacturers and for each of them are specified all models when or was issued, i.e. can be more than 100. Total to load some tens thousand itemov in javascript there is no the best variant). Besides will be come to write not such and idle time javaskript. Plus can be a situation when the data should be interactive.


Let's try to solve it with help AJAX.


For this purpose we create usual ASPX page:



<form id = "form1" runat = "server">

  <div>

      <table>

          <tr>

              <td>

                  Please, select Manufacturer:

              </td>

              <td>

                  <asp:DropDownList runat = "server" ID = "ddlManufacturer"> </asp:DropDownList>

              </td>

          </tr>

          <tr>

              <td>

                  Please, select Model:

              </td>

              <td>

                  <asp:DropDownList runat = "server" ID = "ddlModel"> </asp:DropDownList>

              </td>

          </tr>

      </table>

  </div>

  </form>


Then we sell interface ICallbackEventHandler for a class of page:



public partial class CarList: System. Web. UI.Page, ICallbackEventHandler

  {

      protected string evArg;

      protected void Page_Load (object sender, EventArgs e)

      {

}

      *region ICallbackEventHandler Members

      public string GetCallbackResult ()

      {

          throw new Exception (" The method or operation is not implemented. ");

}

      public void RaiseCallbackEvent (string eventArgument)

      {

          throw new Exception (" The method or operation is not implemented. ");

}

      *endregion

}


It is necessary for us to receive eventArgument in method RaiseCallbackEvent, to make corresponding actions and then to pass it{him} in GetCallbackResult for return to the client. For this purpose we enter a variable evArg.


Further it is necessary for us to fasten client obrabotchik for the first SELECT. I.e. at change of value function WebForm_DoCallback should be caused. And we write J



protected void Page_Load (object sender, EventArgs e)

  {

  string argClientFunction = " document.all [' " + ddlManufacturer. ClientID + " '] .options (document.all [' " + ddlManufacturer. ClientID + " '] .selectedIndex) .value ";

  string cScript = ClientScript. GetCallbackEventReference (this, argClientFunction, "CallbackFunction", "'CallbackContext'", "null", false);

  ddlManufacturer. Attributes. Add ("onchange", cScript + "; return false; ");

}


Now we shall write 2 methods, first of which it is necessary only once - for binding the list of manufacturers, and the second - for the list of models. That not muchat`sja from a DB we shall make easier as follows:



void BindManufacturers ()

      {

          ddlManufacturers. Items. Add (new ListItem ("Mercedes"));

          ddlManufacturers. Items. Add (new ListItem ("BMW"));

          ddlManufacturers. Items. Add (new ListItem ("Renault"));

          ddlManufacturers. Items. Add (new ListItem ("Toyota"));

          ddlManufacturers. Items. Add (new ListItem ("Daewoo"));

}

      void BindModels (string manufacturer)

      {

          switch (manufacturer)

          {

              case "Mercedes":

                  ddlModel. Items. Clear ();

                  ddlModel. Items. Add (new ListItem ("S350"));

                  ddlModel. Items. Add (new ListItem ("S500"));

                  ddlModel. Items. Add (new ListItem ("S600"));

                  ddlModel. Items. Add (new ListItem ("CLK"));

                  break;

              case "BMW":

                  ddlModel. Items. Clear ();

                  ddlModel. Items. Add (new ListItem (" model 3 "));

                  ddlModel. Items. Add (new ListItem (" model 5 "));

                  ddlModel. Items. Add (new ListItem (" model 7 "));

                  ddlModel. Items. Add (new ListItem ("X3"));

                  ddlModel. Items. Add (new ListItem ("X5"));

                  break;

              case "Renault":

                  ddlModel. Items. Clear ();

                  ddlModel. Items. Add (new ListItem ("12"));

                  ddlModel. Items. Add (new ListItem ("19"));

                  ddlModel. Items. Add (new ListItem ("21"));

                  break;

              case "Toyota":

                  ddlModel. Items. Clear ();

                  ddlModel. Items. Add (new ListItem ("Aristo"));

                  ddlModel. Items. Add (new ListItem ("Avalon"));

                  ddlModel. Items. Add (new ListItem ("Avensis"));

                  ddlModel. Items. Add (new ListItem ("Bandeirante"));

                  break;

              case "Daewoo":

                  ddlModel. Items. Clear ();

                  ddlModel. Items. Add (new ListItem ("Sens"));

                  ddlModel. Items. Add (new ListItem ("Lanos"));

                  break;

}

}


And therefore to fill in the list of manufacturers, it is necessary to add in Page_Load:



if (! IsPostBack)

              BindManufacturers ();


Now it are necessary to make 2 things - to write client function which will be carried out after return and to write a code for functions RaiseCallbackEvent and GetCallbackResult.


First we shall write a code for these 2 functions:



public string GetCallbackResult ()

      {

          BindModels (evArg);

          evArg = String. Empty;

          for (int i = 0; i <ddlModel. Items. Count; i ++)

          {

              evArg + = ddlModel. Items [i] .Value + ";";

}

          return evArg;

}

      public void RaiseCallbackEvent (string eventArgument)

      {

          evArg = eventArgument;

}


Option value eventArgument functions RaiseCallbackEvent it is brought in an internal variable evArg (this value of the chosen manufacturer), and in GetCallbackResult perebindiv the list of models in the same variable is brought all values of models for the given manufacturer, having divided{shared} them for example ";" (a such way of serialization).


Further we shall write client function CallbackFunction. The given function should clear SELECT for models and, having received line value from GetCallbackResult, deserializirovat` in this value and to fill SELECT new values.



string scr = " <script language=javascript> ";

  scr + = " function CallbackFunction (callbackResult, callbackContext) ";

  scr + = "{";

  scr + = " var ddlModel = document.all [' " + ddlModel. ClientID + " ']; ";

  scr + = " var l = ddlModel.options.length; ";

  scr + = " for (var i=0; i <l; i ++) ";

  scr + = " ddlModel.options.remove (0); ";

  scr + = " var models = callbackResult.split (';'); ";

  scr + = " for (var i=0; i <models.length; i ++) ";

  scr + = "{";

  scr + = " var oOption = document.createElement ("OPTION"); ";

  scr + = " oOption.text = models [i]; ";

  scr + = " oOption.value = models [i]; ";

  scr + = " ddlModel.options.add (oOption); ";

  scr + = "}";

  scr + = " return false; ";

  scr + = "}";

  scr + = "</script>";

  RegisterStartupScript ("scr" + this. ClientID, scr);


Basically and all. The given example certainly is not perfect (for example, processing of mistakes) is not taken into account{discounted}, but is quite efficient.

Bibloteka ATLAS


To facilitate a life to the simple programmer at job with AJAX and to relieve it{him} of necessity to penetrate into details of interaction of the client with the server - Microsoft has developed the library containing a number{line} of components, using AJAX. For the majority of cases at use of these components even there is no necessity to know principles of job AJAX. Components ATLAS are placed on aspx-page is similar to the user components (as a matter of fact them and being) so programming with their use by anything essentially does not differ from programming with use of the user components. Microsoft constantly updates this list, therefore I would advise more often to visit{attend} a web-site http://atlas.asp.net for updating the current used version on newer (besides new ATLAS-kontrolov or earlier kontrolov, but with the corrected mistakes it is possible to take intermediate versions from a site:...).


To add in project ATLAS components it is necessary to be convinced first, that ATLAS it is established on your computer, otherwise it{him} to establish. Then it is possible or to create the project such as "ATLAS" Web Site, or to add the link to library. In the second case it is necessary to adjust also web.config to use ATLAS manually.


At the moment of a spelling of clause{article} ATLAS included 21 kontrol, some of which are used enough often, personally I except for as in test applications anywhere did not use others. Kontrol CascadingDropDown is ATLAS realization of that we have written above J Most shirokoispol`zuemyj and universal, in my opinion, it kontrol UpdatePanel is a panel (on the client she will be transformed in div an element) with which it is possible to overload not overloading page, and she can contain others kontroly. UpdatePanel will consist of 2 parts - ContentTemplate and Triggers. ContentTemplate represents area of contents ContentTemplate (i.e. as I already spoke, it can be from others ASP.NET kontrolov, tegov HTML and simply the text). Triggers contains the list of triggers for given UpdatePanel. The trigger is as though obrabotchik events on which given UpdatePanel it should be updated. Triggers are 2 types - ControlEventTrigger and ControlValueTrigger. First of them reacts to events kontrola (for example, kontrolom event Click is Button and perekhvatyvaemym event), the second - on change of property (for example change of value Text for kontrola TextBox). For example, the following code:



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

  <head runat = "server">

      <title> Untitled Page </title>

      <atlas:ScriptManager EnablePartialRendering = "true" ID = "scriptManager" runat = "server"> </atlas:ScriptManager>

  </head>

  <body>

      <form id = "form1" runat = "server">

      <div>

          <atlas:UpdatePanel runat = "server" ID = "myUpdatePanel" Mode = "Conditional">

              <ContentTemplate>

                <asp:Label runat = "server" ID = "lbl"> </asp:Label>

              </ContentTemplate>

              <Triggers>

                <atlas:ControlEventTrigger ControlID = "btn" EventName = "Click"/>

              </Triggers>

          </atlas:UpdatePanel>

          <br/>

          <asp:Button runat = "server" ID = "btn" Text = " Click Me " OnClick = "btn_Click"/>

      </div>

      </form>

  </body>

  </html>

  public partial class test_ajax1: System. Web. UI.Page

  {

      protected void Page_Load (object sender, EventArgs e)

      {

}

      protected void btn_Click (object sender, EventArgs e)

      {

          lbl. Text = " Button was clicked ";

}

}


Will update value Label on pressing the button with use AJAX. Pay attention, that the given code practically differs nothing from "classical" ASP.NET a code. Having moved Label from UpdatePanel - we shall receive a "classical" variant: the button has been pressed - the search to the server is made - the page has passed a full cycle of loading of page - value of element Label is updated - the page is returned to the client. It allows to adapt easily under use ATLAS and on the contrary. However there is one more line in a code to which you probably have not paid attention are ScriptManager in heading of page. The given element adds in page returned to the client all necessary for ATLAS client scripts and this element is obligatory (and in the single copy on page) in case of use ATLAS. Also I want to warn, that in case of use ControlValueTrigger it is necessary on checked kontrol AutoPostBack = "true", differently he it will not be simple to work. To strengthen the knowledge and to try use ATLAS in practice we create the elementary chat. But in our chat there will be one feature - he will use AJAX technology and due to this he will be interactive. In chats of former times it was necessary or from time to time (for example everyone 20 sek) to overload all page - thus some large lacks at once emerged:


1. (and the biggest) if the user typed{collected} the text and during this moment time of an overload approached{suited} - the user lost focus of input and accordingly that part of the message which he has already typed{collected}

2. The overload kept the user waiting, while the page will be loaded and according to him it was necessary to contemplate on a blank page with the indicator of loading below

3. It was impossible to make an overload too often since besides the text it was necessary to download also all attributes of page - a picture, trade marks, banners, marking HTML


For struggle against this phenomenon began to use frames that allowed to overload only one frame, thus the user did not lose focus and it was not necessary to load a part of page that is outside of the given frame. However lacks as the overloaded frame with a white background and rezmetka HTML have all the same remained, plus to them lacks of use of frames were added. Use AJAX allows to get rid completely of all these lacks - the data are passed only what it is necessary, namely only the text (without marking HTML - the marking is established javascript'om) and in an optimum variant only NEW messages (thus old as required leave also javascript'om). Thus decrease{reduction} in the traffic in hundreds, and even thousand, time allows to reduce time between searches down to several seconds. Thus the user does not see process of loading - it seems to him, that all occurs by his{its} machine.


In view of all opportunities AJAX I shall give creation of such chat to the reader, and with use of component ATLAS - UpdatePanel - we shall create now.



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

  <head runat = "server">

      <title> Untitled Page </title>

      <atlas:ScriptManager EnablePartialRendering = "true" ID = "scriptManager" runat = "server"/>

  </head>

  <body>

      <form id = "form1" runat = "server">

      <div>

          <atlas:UpdatePanel runat = "server" ID = "up" Mode = "Conditional">

              <ContentTemplate>

                  <asp:Literal runat = "server" ID = "lc"> </asp:Literal>

              </ContentTemplate>

              <Triggers>

                <atlas:ControlEventTrigger ControlID = "btn" EventName = "Click"/>

              </Triggers>

          </atlas:UpdatePanel>

          <br/>

          <table>

              <tr>

                  <td> Your name: </td>

                  <td>

                      <asp:TextBox runat = "server" ID = "txtName"> </asp:TextBox>

                  </td>

              </tr>

              <tr>

                  <td> Your Message: </td>

                  <td>

                      <asp:TextBox runat = "server" ID = "txtMessage" TextMode = "MultiLine"> </asp:TextBox>

                  </td>

              </tr>

              <tr>

                  <td colspan = "2">

                      <asp:Button runat = "server" ID = "btn" Text = " Add message " OnClick = "btn_Click"/>

                  </td>

              </tr>

          </table>

      </div>

      </form>

  </body>

  </html>

  public partial class chat: System. Web. UI.Page

  {

      protected void Page_Load (object sender, EventArgs e)

      {

}

      protected void btn_Click (object sender, EventArgs e)

      {

          string mes = txtName. Text + " says> " + txtMessage. Text + "<BR>";

          // We use the most accessible storehouse for messages - Application.

          if (Application ["messages"] == null)

          {

              Application ["messages"] = mes;

}

          else

          {

              Application ["messages"] = ((string) Application ["messages"]) + mes;

}

          lc. Text = Application ["messages"] .ToString ();

}

}


In the given example the trigger for UpdatePanel hangs on the button btn, i.e. UpdatePanel will be updated only in case of pressing this button. It is necessary for us that UpdatePanel it was updated also through the certain time intervals. There are no standard ways to force to be updated UpdatePanel with the help javascript. I do{make} it as follows:


1. On the form I add one more button and I do{make} its{her} invisible.



<asp:Button runat = "server" ID = "btnUpdate" Visible = "false"/>


2. I create following{next} javascript:



string scr = " <script language=javascript> ";

          scr + = " function UpdatingPanel () ";

          scr + = "{";

          scr + = " " + Page. ClientScript. GetPostBackEventReference (btnUpdate, " ") + ";";

          scr + = "}";

          scr + = "</script>";

          RegisterStartupScript ("scr" + this. ClientID, scr);


3. In UpdatePanel I add the trigger for this button:



<atlas:ControlEventTrigger ControlID = "btnUpdate" EventName = "Click"/>


Also it is necessary to register in <% Page %> - EnableEventValidation = "false"


4. And also in teg body: onload = " setInterval (' UpdatingPanel () ', 3000); "


As it works - client function UpdatingPanel roughly speaking simulates pressing the button btnUpdate. Since in UpdatePanel there is a trigger for this button - that the call of this klienskoj functions will call updating UpdatePanel. We need to cause only this client function through the certain time intervals, that we and do{make} in body.


In result at us the following code has turned out:



<% Page Language = " C * " AutoEventWireup = "true" CodeFile = "chat.aspx.cs" Inherits = "test_chat" EnableEventValidation = "false" %>

  <% Register Assembly = "AtlasControlToolkit" Namespace = "AtlasControlToolkit" TagPrefix = "atlasToolkit" %>

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

  <head runat = "server">

      <title> Untitled Page </title>

      <atlas:ScriptManager EnablePartialRendering = "true" ID = "scriptManager" runat = "server"/>

  </head>

  <body onload = " setInterval (' UpdatingPanel () ', 3000); ">

      <form id = "form1" runat = "server">

      <div>

          <asp:Button runat = "server" ID = "btnUpdate" Visible = "false"/>

          <atlas:UpdatePanel runat = "server" ID = "up" Mode = "Conditional">

              <ContentTemplate>

                  <asp:Literal runat = "server" ID = "lc"> </asp:Literal>

              </ContentTemplate>

              <Triggers>

                  <atlas:ControlEventTrigger ControlID = "btn" EventName = "Click"/>

                  <atlas:ControlEventTrigger ControlID = "btnUpdate" EventName = "Click"/>

              </Triggers>

          </atlas:UpdatePanel>

          <br/>

          <table>

              <tr>

                  <td> Your name: </td>

                  <td>

                      <asp:TextBox runat = "server" ID = "txtName"> </asp:TextBox>

                  </td>

              </tr>

              <tr>

                  <td> Your Message: </td>

                  <td>

                      <asp:TextBox runat = "server" ID = "txtMessage" TextMode = "MultiLine"> </asp:TextBox>

                  </td>

              </tr>

              <tr>

                  <td colspan = "2">

                      <asp:Button runat = "server" ID = "btn" Text = " Add message " OnClick = "btn_Click"/>

                  </td>

              </tr>

          </table>

      </div>

      </form>

  </body>

  </html>

  public partial class chat: System. Web. UI.Page

  {

      protected void Page_Load (object sender, EventArgs e)

      {

          string scr = " <script language=javascript> ";

          scr + = " function UpdatingPanel () ";

          scr + = "{";

          scr + = " " + Page. ClientScript. GetPostBackEventReference (btnUpdate, " ") + ";";

          scr + = "}";

          scr + = "</script>";

          RegisterStartupScript ("scr" + this. ClientID, scr);

          InitMessage ();

}

      void InitMessage ()

      {

          if (Application ["messages"]! = null)

              lc. Text = Application ["messages"] .ToString ();

}

      protected void btn_Click (object sender, EventArgs e)

      {

          string mes = txtName. Text + " says> " + txtMessage. Text + "<BR>";

          if (Application ["messages"] == null)

              Application ["messages"] = mes;

          else

              Application ["messages"] = ((string) Application ["messages"]) + mes;

          lc. Text = Application ["messages"] .ToString ();

}

}


To try this elementary variant of a chat with use ATLAS in practice - open some browsers with the given page and in each of them write under the message. Thus can see, that after a spelling in the second browser of the message in the first it will appear after 3 seconds.



In given clause{article} I have described bases of job with AJAX in ASP.NET and I hope, that she will help programmers to begin use of this technology in the ASP.NET applications.


P.S. When this clause{article} was written to last day Microsoft has issued instead of ATLAS new version AJAX beta 1. How "to migrate" from the application using ATLAS to use AJAX beta 1 you can esteem on page