AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1336&pId=-1
Glitz the Web Pages in Your ASP.NET AJAX Based Applications - Part 1
page
by Xianzhong Zhu
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 29427/ 115

Introduction

When developing a real ASP.NET AJAX framework based web application, we often need to beautify the web pages to attract more web surfers besides giving them the professional and consolidated functions.  With the characteristic behaviors and animated controls supplied by ASP.NET AJAX framework, you can easily achieve your goal.  In this part of the series, I will show you the various glinting features the two ASP.NET 2.0 AJAX Futures January CTP libraries - PreviewGlitz and PreviewDragDrop -bring to us through concrete and distinct samples.  In the first installment of this series we will examine the four kinds of built-in behavior effects.

Requirements

First, the testing environment we will use here is Windows XP Professional (with IIS installed), Visual Studio 2005.  Second, we assume that you have installed the three components of the ASP.ET AJAX framework: ASP.NET AJAX Essential Components, ASP.NET AJAX Futures January CTP, and ASP.NET AJAX Control Toolkit (although not very necessary, but I highly recommend installing it for related comparison).  Third, to follow along with the examples, you need to download the source files accompanying this article (see the downloads section at the end of the article).

Behavior

Introducing Behavior

There are three types of ASP.NET AJAX client component objects that extend basic component functionality: components that derive from Sys.Component, behaviors that derive from Sys.UI.Behavior, and controls that derive from Sys.UI.Control.  Their differences are summarized in the following table.

Client component object types

Summary

Components

Derive from the Sys.Component.

Typically have no physical UI representation, such as a timer component that raises events at intervals but is not visible on the page.

Have no associated DOM elements.

Encapsulate client code intended to be reusable across applications.

Derive from the Component base class.

Behaviors

Derive from Sys.UI.Behavior.

Extend the behavior of DOM elements, such as a watermarking behavior that can be attached to an existing text box.

Can create UI elements, although they do not typically modify the markup of the associated DOM element that they are attached to.

If assigned an ID, can be accessed directly from the DOM element through a custom attribute (expando).

Do not require an association with another client object, such as a class derived from the Control or Behavior classes.

Can reference either a control or a non-control HTML element in their element property.

Derive from the Behavior base class, which extends the Component base class.

Controls

Derive from Control.

Represent a DOM element as a client object, typically changing the original DOM element's normal behavior to provide new functionality. For example, a menu control might read items from a <ul> element as its source data, but not display a bulleted list.

Accessed from the DOM element directly through the control expando.

Derive from the Control base class, which extends the Component base class.

Note the online tutorial provides excellent samples on how to use the above three types of ASP.NET AJAX client component objects (mainly customized ones) to enhance the capacities of server-side controls and client-side controls (mainly wrappers for common HTML DOM elements).  In this installment, therefore, we will concentrate on four common built-in Behavior-derived classes.

We will start with ClickBehavior.

Using behavior ClickBehavior—Example 1

Many MS AJAX client-side controls support a click event for common user input; nevertheless, not all the controls support the click event handler to allow the developers to specify the corresponding function.  For this, MS AJAX provides a built-in Behavior named ClickBehavior to permit developers to attach the click behavior to the client-side controls without the click event.  In the following example we will use a MS AJAX client-side Label control to encapsulate a passage of text and then attach the click behavior to it, through which we will succeed in simulating the click event.  To further grasp the usage of ClickBehavior (of course suitable for all the other kinds of behaviors, including built-in and customized ones) we will use two programming modes—JavaScript (imperative) and xml-script (declarative) in Example 1.  First look at the xml-script mode, i.e. declarative mode.

1. Declarative Mode

We will start Visual Studio 2005 and select the "ASP.NET AJAX CTP-Enabled Web Site" template to create a new website and name it GlitzTest.  Then right-click the project and add a new web page named InitialClickBehavior.aspx.  The following figure shows its design-time snapshot.

Figure 1: the design-time snapshot for Example 1

As you see from the above figure, the Hide and Show buttons here are not true HTML Button elements.  However, they are HTML span elements and they can support clicking event using the click behavior on their associated ASP.NET AJAX labels.  The associated HTML code is pretty simple.

Listing 1: The main HTML code for page InitialClickBehavior.aspx

<asp:ScriptManager runat="server" ID="ScriptManager1" >
      <Scripts>
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="PreviewScript.js" />
      </Scripts>
</asp:ScriptManager>
<h3><u><span style="font-size: 24pt; color: #000099;">
Click behavior Test</span></u></h3>
 
<div id="Div1" class="">
      <span style="font-size: 16pt">
          The hide and show elements here are not buttons .<br />
      They are HTML spans, but they can support clicking through 
      <br />
      use of the click behavior on their associated ASP.NET AJAX labels. 
      <br />
      <span style="color: #ff9966">
          Just click the 'buttons' to see what happens.<br />
      </span>
</span>
</div>
<hr style="border-bottom: blue thick solid; color: #000000;" />
<div id="panel">     
      <img src="img/lushan_1.jpg" style="width: 188px; height: 192px" /><br />
</div>
 
<hr style="border-bottom: blue thick solid; color: #000000;" />
<span id="hideLabel" class="buttonstyle2">Hide</span>&nbsp;
<span id="showLabel" class="buttonstyle2">Show</span>

First, we create an instance of the server control ScriptManager which is the control center of whole MS AJAX framework.  Next, because ClickBehavior is defined in PreviewScript.js (included in Futures CTP), we add a reference to assembly Microsoft.Web.Preview.dll as well as specifying the related JavaScript file within it.  Notice that button Hide and Show are virtually <span> labels.  Next, look into the more interesting xml-script part in Listing 2.

Listing 2

<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
      <control id="panel"/>
      <label id="hideLabel">
            <behaviors>
                  <ClickBehavior>
                        <click>
                              <SetPropertyAction target="panel" property="visible"
                                  value="false" />
                        </click>   
                  </ClickBehavior> 
            </behaviors>
      </label>
      <label id="showLabel">
            <behaviors>
                  <clickBehavior>
                        <click>
                              <SetPropertyAction target="panel" property="visible"
                                  value="true" />
                        </click>   
                  </clickBehavior> 
            </behaviors>
      </label>
      <application>
            <load>
                  <invokeMethodAction target="panel" method="addCssClass">
                      <parameters   className="start"/>
                  </invokeMethodAction>
            </load>
      </application>
</components>
</page>
</script>

Here, the two HTML <span> labels are encapsulated by two MS AJAX client-side Label controls whose behaviors are declared with <behaviors> tags.  Because here we need to use clickBehavior, we add the clickBehavior tag as a sub node to node <behaviors>.  Next, we set property visible of target "panel" to true/false using the click event of clickBehavior and action SetPropertyAction.  When users click "hideLabel," behavior clickBehavior will trigger the click event which in turn will invoke SetPropertyAction to set property visible of "panel" to false. Similar things happen to "button" showLabel.  A control that does not support click event now has been added a click event and behaviors to respond to it!  Also, we should notice that within the subsection <load> (i.e. the load event of Application object) of section <application> the style of "panel" has been modified with a css class start defined in file intro.css by calling method addCssClass of control "panel"—we will not dwell on it since this is off topic.

Author's Notes: Although MS AJAX client-side Control still supports the css-related methods—addCSSClass, removeCSSClass, and toggleCSSClass (defined within its prototype block), it does not support property cssClass in the recent Futures CTP any more.

In the following section, let us find out how the other equivalent programming mode (JavaScript programming) works.

2. Imperative Mode

For easier comparison, I created another web page, InitialClickBehavior2.aspx, with the same HTML code as page InitialClickBehavior.aspx.  The following listing gives the equivalent imperative programming.

Listing 3

<script type="text/javascript">
function pageLoad(sender, args) {
      //attach behavior ClickBehavior to HTML labels
      $create(
            Sys.Preview.UI.ClickBehavior, 
            {name: "initialClickBehavior1"},
            {click:onSetInvisible}, 
            null, 
            $get("domhideLabel")
      );
      $create(
            Sys.Preview.UI.ClickBehavior, 
            {name: "initialClickBehavior2"},
            {click:onSetVisible}, 
            null, 
            $get("domshowLabel")
      );
}
function onSetInvisible()
{
      var pa1=new Sys.Preview.SetPropertyAction();
      pa1.set_target($find("panel"));
      pa1.set_property("visible");
      pa1.set_value("false");
      pa1.performAction();
}
function onSetVisible()
{
      var pa2=new Sys.Preview.SetPropertyAction();
      pa2.set_target($find("panel"));
      pa2.set_property("visible");
      pa2.set_value("true");
      pa2.performAction();
}
</script>

First note that, for simplicity, we have still used the <application> section (omitted here) in Listing 2.  Thus, we first attach behavior ClickBehavior to two HTML labels by calling an important global method—$create.  For your convenience, we will give a detailed explanation.  First, within file MicrosoftAjax.js, there is the following line.

Listing 4

var $create = Sys.Component.create……(omitted)

Obviously, $create is the equivalence of method Sys.Component.create.

Second, the basic syntax form of method $create is below.

Listing 5

$create(type, properties, events, references, element);

Third, each related argument is explained in the following table.

Parameter

Description

type

The type of the component to create.

properties

A JSON object that contains a component ID value and optionally any initial property name/value pairs.

events

An optional JSON object that contains the event name and event/handler binding pairs (i.e. the events and their handlers).

references

(Optional) A JSON object that describes the properties that are references to other components.

element

(Optional) The DOM element that the component must be attached to.

 

Now, everything becomes clear with the first $create; we have instantiated a client component, Sys.Preview.UI.ClickBehavior, specified its name "initialClickBehavior1," attached its click event to an event handler (onSetInvisible), and bonded the behavior to the DOM element domhideLabel.  In the case of the second $create, things are quite similar with this.

When users click the Hide button, the click event handler onSetInvisible of initialClickBehavior1 will be invoked. And next, the executive routine is directed into function onSetInvisible; we first create an instance of Sys.Preview.SetPropertyAction named pa1, and then set its required parameters and finally call method performAction to execute Action pa1 to make its target "panel" invisible.  Here you must use $find instead of $get—for more differences between them, please refer to the online tutorial.  As for the other event handler, onSetVisible, things are also quite the same.

Obviously, in this demo the xml-script mode shows its predominance over the trivial JavaScript programming (and with poor API referrence).

Using behavior FloatingBehavior - Example 2

FloatingBehavior is a kind of Behavior that can make both server-side and client-side control floatable and draggable on the web page with which we can easily achieve the similar dragging effect of the famous Live.com or Start.com, which permit users to rearrange the gadgets on the web pages according to their preferences.  Here we are to build a simple demo to illustrate the basic using routine of FloatingBehavior.

With project GlitzTest still open, right-click the project and add a new web page named MyFloatingBehavior.aspx.   Then, with a little modification, the final web page should look like Figure 2.

Figure 2: The design-time snapshot for the floating behavior

Here, just for demonstration we put a <img> element and a <div> element on the page.  With the application started, you can try dragging any part of the two objects freely wherever on the page.  When you release the mouse button, the object you are dragging will stay at the place you have just stopped.  Please note that since FloatingBehavior comes from file PreviewDragDrop.js, we must add the related reference to it (see the downloadable source code). And for brevity, we are only going to examine the script part that interests us.

Listing 6

<script type="text/xml-script">
<page xmlns:script="http://.../xml-script/2005">
      <components>
            <control id="draghandler">
                  <behaviors>
                        <floatingBehavior handle="draghandler" />
                  </behaviors>
            </control>
      </components>
</page>
</script>
 
<script type="text/javascript">
function pageLoad()
{
      var float1 = new Sys.Preview.UI.FloatingBehavior($get('FloatMe'));
      float1.set_handle($get('FloatMe'));
      float1.initialize();
}
</script>

In the above Listing, we have still used two programming modes to give clearer compassion.  First, for the <div> object (with id being draghandler) in Figure 2, we have simply attached an anonymous instance of behavior FloatingBehavior to achieve the dragging effect.  Second, in the public event pageLoad of Application, we created another instance of FloatingBehavior with variable float1 pointing to it. Note we have to specify the parameter of function FloatingBehavior (its definition being "Sys.Preview.UI.FloatingBehavior=function(a){…"), otherwise you will get a run-time error.  Next, we attach the newly-created behavior instance to the client-side (again can also be server-side) target control—the shopping cart picture.  Finally, we call method initialize to get everything ready.

Author's Notes: First, because Behavior cannot exist independently, it must be used as a sub-section put under some control-related section.  And therefore, we must make clear the usage of property handle of FloatingBehavior.  The handle property is used to specify the special area within the "parent" control that has been attached to the behavior, such as the title part of a simulated dialog window, where we wish the user can only drag the title bar to move the window, so we can set the handle property of an instance of behavior FloatingBehavior to the related ID of the title bar.  Second, by further digging into the file PreviewDragDrop.js, we can easily find that behavior FloatingBehavior has also implemented two other important interfaces—Sys.Preview.UI.IDragSource and Sys.Preview.UI.IDropTarget - and provided many other methods.  So you can image the capacities this behavior holds are far more than dragging.  Therefore, I highly recommend you further study it in combination with other drag & drop related ASP.NET AJAX Control Toolkit controls.

Using behavior OpacityBehavior - Example 3

OpacityBehavior is a behavior used to control the opacity of the controls on the web page.  This class has supplied only one property "value."  By controlling the transparency (or opacity) of the target control we can obtain some wonderful visual effect, such as when the user moves the mouse over the control.  However, here we only discuss the simplest situation—to display pictures with different values of opacity.  Now, with the above project still open, right-click it and add a new web page and name it OpacityBehavior.aspx.  Figure 3 illustrates the design-time snapshot of the web page.

Figure 3: The design-time snapshot of page OpacityBehavior.aspx

Since the layout of the page and controls on it can be easily doped out, we no more list the associated HTML code.  Here, we have defined three <img> elements which will be displayed at run-time with different opacities.  Since OpacityBehavior is defined in file PreviewGlitz.js, we should add the reference to it within the sub section </Scripts> of section </asp:ScriptManager>.  Next, let us focus on the crucial xml-script declarative part in Listing 7.

Listing 7

<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
      <components>
            <image id="i1" >
                  <behaviors>
                        <OpacityBehavior value="0.2">
                        </OpacityBehavior>
                  </behaviors>
            </image>
            <image id="i2" >
                  <behaviors>
                        <OpacityBehavior value="0.5">
                        </OpacityBehavior>
                  </behaviors>
            </image>
            <image id="i3" >
                  <behaviors>
                        <OpacityBehavior value="0.8">
                        </OpacityBehavior>
                  </behaviors>
            </image>
      </components>
</page>
</script>

Here, the logic is very simple.  We attached three OpacityBehaviors with different opacities to three different images.  Just press F5 and you will see the run-time result as shown in Figure 4.

Figure 4: The run-time snapshot for pictures with different opacity values

OK, that is it!  As for the case of showing with different transparency with the mouse over different areas, I will to leave it to the readers (you can download the older Atlas.js for reference because HoverBehavior is in it, but regrettably it has been deleted in the newest version inexplicably).

Using behavior LayoutBehavior - Example 4

LayoutBehavior is a kind of Behavior that can specify the size and position of controls on the web page at run-time.  This behavior provides simple functions to control the target elements, whose simple descriptor definition is shown in the following listing.

Listing 8

Sys.Preview.UI.Effects.LayoutBehavior.descriptor={
      properties:[{
      name:"height",type:String},{
      name:"left",type:String},{
      name:"top",type:String},{
      name:"width",type:String}]
};

In real scenarios, we often combine behavior LayoutBehavior with other kinds of behaviors to achieve the wanted effects.  So, in the following sample we will use three types of behaviors, FloatingBehavior, OpacityBehavior and LayoutBehavior, to win better visual effect.

Now, open project GlitzTest using Visual Studio 2005 and right-click the project to add a new web page named LayoutBehavior.aspx.  Then, with a little modification, the final web page should look like Figure 5.

Figure 5: The design-time snapshot for the floating & opacity & layout behavior

We have integrated three kinds of behaviors, FloatingBehavior, OpacityBehavior and LayoutBehavior, together into this demo.  Despite this, this sample is still pretty simple. Listing 9 shows the HTML code definitions.

Listing 9: The main HTML code definitions for page LayoutBehavior.aspx

<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1">
      <Scripts>
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" 
                Name="PreviewScript.js" />
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" 
                Name="PreviewDragDrop.js" />
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" 
                Name="PreviewGlitz.js" />
      </Scripts>
</asp:ScriptManager>
<div class="description">
<h3><u><span style="font-size: 24pt; color: #000099;">
Floating, Opacity and Layout Behaviors Test</span></u></h3>
<br />
<br />
 
<div id="Description">
<div id="DragHandle" style="text-align:center;font-weight:bold; 
    border-right: #ff3333 thin dotted; border-top: #ff3333 thin dotted; 
    border-left: #ff3333 thin dotted; border-bottom: #ff3333 thin dotted; 
    background-color: #ff99cc;">
Drag by clicking on this element
</div>
<div >Pane 1</div>
HTML For Pane 1. This is set to opacity 0.2
</div>
<br />
<br />
<div id="Description2">
<div id="DragHandle2" style="border-right: aqua thick inset; 
    border-top: aqua thick inset; border-left: aqua thick inset; 
    border-bottom: aqua thick inset; 
    background-color: #ffcc66;">Drag by clicking on this element</div>
<div style="text-align:center;font-weight:bold;">Pane 2</div>
HTML For Pane 2. This is set to opacity 0.5</div>
<br />
</div>
</form>

First, within section <asp:ScriptManager> we added the necessary reference to assembly Microsoft.Web.Preview.dll, as well as the required *.js files contained in it.  Next, we used two <div> labels—Description and Description2 to simulate two windows on the web page, with their inner <div> labels—DragHandle and DragHandle2 - simulating their window titles, respectively.  Here, for more legible effect, we used a little CSS skill.  Start to check out how we accomplish this task through MS AJAX client-side xml-script programming.

Listing 10

<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
      <components>
            <control id="DragHandle"  />
            <control id="Description" >
                  <behaviors>
                        <floatingBehavior handle="DragHandle">
                        </floatingBehavior>
                        <OpacityBehavior value="0.2">
                        </OpacityBehavior>
                        <LayoutBehavior id="myLo" top="100" left="100"
                            height="100" width="100">
                        </LayoutBehavior>
                  </behaviors>
            </control>
 
            <control id="DragHandle2" /> 
            <control id="Description2" >
                  <behaviors>
                        <floatingBehavior handle="DragHandle2">
                        </floatingBehavior>
                        <OpacityBehavior value="0.5">
                        </OpacityBehavior>
                        <LayoutBehavior id="myLo2" top="100" left="300"
                            height="100" width="100">
                        </LayoutBehavior>
                  </behaviors>
            </control>
      </components>
</page>
</script>

As is seen from Listing 10, we used two groups of <div> labels to simulate two windows to gain better comparative result, which utilized the similar layouts and were attached to by similar behaviors.

By using floatingBehavior we can make the target controls floating on the page and draggable; by using OpacityBehavior, we can control the transparency of the target controls, and by using LayoutBehavior, we can adjust the size and position of the target controls at run-time.  The following figure corresponds to the run-time snapshot grabbed at some time.

Figure 6: The run-time snapshot for the composite behaviors effect

From above, we can see that not only the size and position of the two "windows" changed, but also the transparency of them altered according to the configured value at the design-time.  Also, if you drag either rectangular area of the two "windows," you can of course drag them anywhere you would like to.  Still simple, isn't it?

Downloads
Summary

On the whole, in this first installment we have only studied the commonly-used built-in Behaviors within MS AJAX Futures CTP, while there are still a wide area for us to explorer, such as the other built-in Behaviors (such as DragDropList, DraggableListItem, etc.) and the more complex custom Behaviors (you can refer to this article and the online tutorial). In addition, we have only scratched the very surface of Behavior (it is one of the powerful approaches to enhance or expand the MS AJAX client-side controls) with simple demos.  In the next installment, we are going to discuss the animating effects supplied by MS AJAX Futures CTP.

Continue Reading Part 2



©Copyright 1998-2018 ASPAlliance.com  |  Page Processed at 2018-01-20 2:05:58 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search