AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=816&pId=-1
Working with AJAX using ATLAS
page
by Sanket Terdal
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 9266/ 12

Introduction

An ASP.NET page processing-model is post-back based.  The older approaches require the reloading of the entire page with every postback.  This means that in order to handle any server side event, you must post the form back to the server.  This event-driven model is certainly powerful and rich, but it has drawbacks of its own.  Today, many browsers support client side JavaScript and DHTML.  The AJAX model is all about making intelligent use of a browser's capabilities to give the user a better experience.  AJAX uses the JavaScript DOM, the XMLHttpRequest object, XML and CSS to download and display just the content that needs to change.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML.  AJAX is by no means a new technology.  The parts of AJAX (i.e. HTML, XML, DOM, XMLHTTP and JavaScript) have been used for years. AJAX refers to use of these individual pieces together.

AJAX techniques reduce round trips to the server (for full page loads, anyway) and enable incremental page UI updates.  Meaning, it avoids full page refreshes. Scenarios in which it can be helpful are data navigation and editing, form validation, auto refresh etc.

XMLHTTPREQUEST object

This object was introduced in recent versions of most popular browsers.  It can perform asynchronous communications with the server - sending and receiving XML data without requiring a complete round trip that regenerates the page.

What is ATLAS?

ATLAS is a new ASP.NET Web development technology that integrates client script libraries with the ASP.NET 2.0 server-based development framework.  ATLAS offers you the same type of development platform for client-based Web pages that ASP.NET offers for server-based pages.  Because "Atlas" is an extension of ASP.NET, it is fully integrated with server-based services.  Using ATLAS, you can move significant portions of an application's processing to the client, while retaining the ability to communicate with the server in the background.  The result is that you can create ASP.NET pages with a rich, responsive UI and server communication.

ATLAS Scenarios

Server-centric Ajax Web Development

·         Incremental Ajax approach to add UI enrichment for key scenarios

·         Enrich applications without a lot of JavaScript code required

·         Enables you to keep core UI/Application logic on server (VB/C#)

Client-centric Ajax Web Development

·         Leverage full power of script/DHTML

·         Provides richer and more interactive user experience

How to use ATLAS in ASP.NET 2.0?

STEP 1

Download and install ATLAS.

By default it will install at <<Windows Root Drive Name >>:\Program Files\Microsoft ASP.NET\Atlas

STEP 2

Copy Microsoft.Web.Atlas.dll from C:\Program Files\Microsoft ASP.NET\Atlas\v2.0.50727\Atlas to your project’s bin folder.

STEP 3

Make changes in Project’s Web.config as shown below.

Listing 1: Web.config

<configSections>
<sectionGroup name="microsoft.web"type="Microsoft.Web.Configuration.MicrosoftWebSectionGroup">
<section name="converters"type="Microsoft.Web.Configuration.ConvertersSection"requirePermission="false"/>
<section name="webServices"type="Microsoft.Web.Configuration.WebServicesSection"requirePermission="false"/>
<section name="authenticationService"type="Microsoft.Web.Configuration.AuthenticationServiceSection"requirePermission="false"/>
<section name="profileService"type="Microsoft.Web.Configuration.ProfileServiceSection"requirePermission="false"/>
</sectionGroup>
</configSections>
 
<microsoft.web>
<converters>
<addtype="Microsoft.Web.Script.Serialization.Converters.DataSetConverter"/>
<addtype="Microsoft.Web.Script.Serialization.Converters.DataRowConverter"/>
<addtype="Microsoft.Web.Script.Serialization.Converters.DataTableConverter"/>
</converters>
<webServicesenableBrowserAccess="true"/>       
</microsoft.web>
 
<pages>
<controls>
<add namespace="Microsoft.Web.UI"assembly="Microsoft.Web.Atlas" tagPrefix="atlas"/>
<addnamespace="Microsoft.Web.UI.Controls" assembly="Microsoft.Web.Atlas"tagPrefix="atlas"/>
</controls>
</pages>
 
<compilation debug="true">
<buildProviders>
<add extension=".asbx"type="Microsoft.Web.Services.BridgeBuildProvider"/>
</buildProviders>
</compilation>
 
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx"type="Microsoft.Web.Services.ScriptHandlerFactory"validate="false"/>                  
<add verb="*"path="atlasbatchcall.axd"type="Microsoft.Web.Services.MultiRequestHandler"validate="false"/>
<add verb="*" path="atlasglob.axd"type="Microsoft.Web.Globalization.GlobalizationHandler"validate="false"/>            
<add verb="*" path="*.asbx"type="Microsoft.Web.Services.ScriptHandlerFactory"validate="false"/>
</httpHandlers>
 
<httpModules>
<add name="ScriptModule"type="Microsoft.Web.Services.ScriptModule"/>
<add name="BridgeModule"type="Microsoft.Web.Services.BridgeModule"/>
<add name="WebResourceCompression"type="Microsoft.Web.Services.WebResourceCompressionModule"/>
</httpModules>

STEP 4

Add runat=server to head tag <head runat=server>.

STEP 5

Add scriptmanager atlas server control at the top of page.

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

Enabling Partial Page Rendering

With partial page rendering, you can specify that when data is updated in a given section of a page only the form data and view-state data in that section are sent back to the server and then re-rendered on the client.  (This is different from standard data applications, where the entire page is sent for every update).  Partial page updates enhance the user experience by making the page seem more responsive and by reducing or eliminating the common flicker often seen after a postback.

STEP 6

Put server control under atlas updatepanel server control as shown in listing 2.

Listing 2: GridView Control inside the atlas updatepanel control

<atlas:ScriptManagerID="scriptManager" runat="server"                    EnablePartialRendering="true"/>
 
<atlas:UpdateProgress  ID="upd" runat=server  EnableViewState=true>
                                                                                                                                           
<ProgressTemplate>
<div class="updateprogress"align=center>
<img src="images/indicator.gif" />
</div>
</ProgressTemplate>
 
</atlas:UpdateProgress>
 
<atlas:UpdatePanel id="u1"runat="server">
<ContentTemplate>
 
<asp:GridView ID="GridView1"  runat="server" AllowPaging="True" AllowSorting="True" cssclass=normal PageSize=3 AutoGenerateColumns="False"
DataKeyNames="TaskID" DataSourceID="SqlDataSource1" width=40%>
 
<Columns>
<asp:TemplateField ShowHeader="False" ItemStyle-HorizontalAlign=center HeaderStyle-HorizontalAlign=Center>
<HeaderStyle  CssClass=NormalBold />
<ItemStyle CssClass=Normal />
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2"runat="server" CausesValidation="False"CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>                      
</ItemTemplate>                        
</asp:TemplateField>
 
<asp:TemplateField HeaderText="TaskList" SortExpression="Task" ItemStyle-HorizontalAlign=centerHeaderStyle-HorizontalAlign=Center>
<HeaderStyle  CssClass=NormalBold />
<ItemStyle CssClass=Normal />
<EditItemTemplate>
<asp:TextBox ID="ListNameEdit"Text='<%# Bind("Task") %>' runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButtonID="ListNameEditButton" Text='<%# Eval("Task") %>'CommandName="Edit" runat="server" />
</ItemTemplate>                       
<HeaderStyle CssClass="name" />
</asp:TemplateField>
                    
<asp:TemplateFieldHeaderText="Priority" SortExpression="Priority"ItemStyle-HorizontalAlign=center HeaderStyle-HorizontalAlign=Center>
<HeaderStyle  CssClass=NormalBold />
<ItemStyle CssClass=Normal />
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1"Width="75" SelectedValue='<%# Bind("Priority") %>'
runat="server">
<asp:ListItem Text="High"Value="High" />
<asp:ListItem Text="Medium"Value="Medium" />
<asp:ListItem Text="Low"Value="Low" />
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="CyclePriority"CssClass="PriorityButton" Text='<%# Eval("Priority")%>' 
CommandArgument='<%# Eval("Priority")%>' CommandName="CyclePriority"OnClick="Priority_Clicked" 
runat="server" />
</ItemTemplate>                       
</asp:TemplateField>
 
<asp:TemplateFieldHeaderText="Completed" SortExpression="Completed" ItemStyle-HorizontalAlign=centerHeaderStyle-HorizontalAlign=Center>
<HeaderStyle  CssClass=NormalBold />
<ItemStyle CssClass=Normal />
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1"runat="server" Checked='<%# Bind("Completed") %>'/>
</EditItemTemplate>                       
<ItemTemplate>
<asp:CheckBox ID="Done"Checked='<%# Eval("Completed") %>' Text=""AutoPostBack="true"
OnCheckedChanged="Completed_CheckedChanged"runat="server" />
</ItemTemplate>
</asp:TemplateField>
 
</Columns>
</asp:GridView>
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:eJobQuestConnectionString%>"
SelectCommand="Select * from Tasks"
UpdateCommand="Update Tasks&#13;&#10;set task= @task,Priority=@Priority,&#13;&#10;Completed=@Completed&#13;&#10;where TaskID = @TaskID">
<UpdateParameters>
<asp:Parameter Name="task" />
<asp:Parameter Name="Priority" />
<asp:Parameter Name="Completed" />
<asp:Parameter Name="TaskID" />
</UpdateParameters>
</asp:SqlDataSource>
</ContentTemplate>        
</atlas:UpdatePanel>

Listing 3: GridView Control inside the atlas updatepanel control  (Code Behind)

Sub Priority_Clicked(ByVal sender As ObjectByVal eAs System.EventArgs)
  Dim btn As LinkButton = CType(sender, LinkButton)
  Dim row As GridViewRow = CType(btn.NamingContainer,GridViewRow)
  Dim strPriority As String = btn.CommandArgument
  If strPriority = "High" Then
    strPriority = "Medium"
  ElseIf strPriority = "Medium" Then
    strPriority = "Low"
  ElseIf strPriority = "Low" Then
    strPriority = "High"
  Else
    strPriority = "High"
  End If
  conn.Open()
  Dim cmd As New SqlCommand("UPDATE Tasks SETPriority = @Priority WHERE
  TaskId = @TaskId", conn)
 
  cmd.Parameters.AddWithValue("Priority",strPriority)
  cmd.Parameters.AddWithValue("TaskId",
  GridView1.DataKeys(row.RowIndex).Value)
  cmd.ExecuteNonQuery()
  System.Threading.Thread.Sleep(200)
  GridView1.DataBind()
End Sub
 
Sub Completed_CheckedChanged(ByVal sender As Object,ByVal e As
  System.EventArgs)
  Dim cbx As CheckBox = CType(sender, CheckBox)
  Dim row As GridViewRow =CType(cbx.NamingContainer, GridViewRow)
  conn.Open()
  Dim cmd As New SqlCommand("UPDATE Tasks SETCompleted = @Completed WHERE
  TaskId = @TaskId", conn)
  cmd.Parameters.AddWithValue("Completed",cbx.Checked)
  cmd.Parameters.AddWithValue("TaskId",
  GridView1.DataKeys(row.RowIndex).Value)
  cmd.ExecuteNonQuery()
  System.Threading.Thread.Sleep(200)
  GridView1.DataBind()
End Sub

Listing 4: Update panel with conditional trigger

<asp:button id="SimplePostBack" onclick="btn2_click"runat="server" Text="SIMPLE POST BACK"/>&nbsp;
<asp:button id="AjaxPostback"onclick="btn1_click" runat="server" Text="AJAX POSTBACK"/>&nbsp;  
<asp:textbox id="TextBox1"runat="server" AutoPostBack="True" Text= "ENTER"/> 
   
<atlas:UpdatePanel id="u2"mode="Conditional" runat="server">
 
<ContentTemplate>
<asp:Label ID=lbl runat=serverText="Display Server Time" CssClass=NormalRed></asp:Label>
</ContentTemplate>
 
<Triggers>   
<atlas:ControlEventTriggercontrolId="AjaxPostBack" EventName="Click" />
<atlas:ControlValueTriggercontrolId="TextBox1" PropertyName="Text"/>
</Triggers>
 
</atlas:UpdatePanel>
 

Listing 5: Update panel with conditional trigger (Code Behind)

Protected Sub btn1_click(ByVal sender As Object,ByVal e As System.EventArgs)
Handles AjaxPostback.Click, SimplePostBack.Click
  lbl.Text = "(AJAX Post Back)Clicked at "Date.Now.ToLongTimeString()
End Sub
 
Protected Sub TextBox1_TextChanged(ByVal sender AsObject, ByVal e As
System.EventArgs) Handles TextBox1.TextChanged
  lbl.Text = "(AJAX Post Back)Textbox text waschanged at " &
  Date.Now.ToLongTimeString()
End Sub
 
Protected Sub btn2_click(ByVal sender As Object,ByVal e As System.EventArgs)
Handles SimplePostBack.Click
  lbl.Text = "(Simple Post Back) Clicked at" & Date.Now.ToLongTimeString()
End Sub

Listing 6: Call Webservice by using JavaScript Function

WebService/WebMethod:

<WebMethod()> _
Public Function AddNumbers(ByVal x As Integer, ByValy As IntegerAs Integer
  Return x + y
End Function

HTML Code:

<input type=text id=Text1 name=Text1 /> +
<input type=text id=Text2 name=Text2 /> =<input type=text id=txtID name=txtName />
<input type="button"value="Result" onclick="Calculate();" />

JavaScript Code

<script type = "text/javascript"language = "javascript" src = "MathWebService.asmx/js"></script>  
<script language = "javascript">
 
function Calculate()
{
 MathWebService.AddNumbers(document.form1.Text1.value,
    document.form1.Text2.value, onComplete);
}
 
function onComplete(result)
{
  document.form1.txtName.value = result;
}
 
</script>

STEP 7

Run the page in the browser and you will feel the difference of using AJAX/Atlas.

ATLAS Live Demo

Click here to view the demo of the above applications.

Conclusion

In this article, we saw how AJAX /ATLAS can help you build more responsive and performance-rich web applications.  Using AJAX, one can call any web resource, including web forms and web services.  AJAX requires a different way of thinking about a web-site, since the concept of a Page is no longer valid here.  And above all, by using AJAX with ATLAS and ASP.NET 2.0, one's perception of web user interface is going to change.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-16 12:58:45 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search