Published: 07 May 2008
By: Xun Ding
Download Sample Code

Leverage the power of ASP .NET server controls and the rich capacity of JavaScript.

Introduction

Before ASP .NET, there was ASP; before ASP, there was JavaScript. While ASP has been gradually marginalized by the rapid succession of ASP .NET 1.x, 2.x and now 3.x, JavaScript remains the sole source and foundation of snappy client-side user experience.

If the time of existence is of any indication, the already gigantic and still rapidly growing repertoire of JavaScript is a force we cannot afford to ignore. The successes of various Google applications offer the best testimony (a testimony for Ajax too).

On the other hand, ASP .NET, especially the vastly improved ASP .NET 2.0 is undeniably a powerful and flexible development environment. The suite of systems (such as membership, role and profile, health monitoring), server controls (GridView, DataList, etc.) and master page, skin and theme relieve programmers much of the burden of doing the same plumbing over and over again, and allow them to concentrate on individual site-based business logic instead.

However the flip side of the coin is the server-centric-ness of ASP .NET. It relies almost exclusively on the server to deal with user interactions. With a slow network connection, ASP .NET applications would seem to be slow responding or not responding at all; if you have a deep-colored background, you get very unpleasant fits of white-flashes. Yes, ASP .NET has taken great effort to address the issues, introduced methods and properties to handle common tasks such as popping up alert or confirmation boxes, setting focus on server controls; created ClientScript class to allow JavaScript to be included with a page or server controls. You may refer to JavaScript with ASP .NET Pages for more details. However, its highly encapsulated declarative-based syntax still poses great challenges for programmers to go beyond the pre-cut patterns and practices and inject into server controls individualized client side responses.

So how do we leverage the power of ASP .NET and the nimbleness of JavaScript to create a powerful website with rich UI experience?

You may say: ASP .NET AJAX.

Yes. And No.

ASP .NET AJAX, or AJAX, is the hotly pursued technology. I, like everyone else, has jumped on this train of Mr. popular. However, like any other technology, ASP .NET technology can be misused and abused.

In a blog article entitled "Past the AJAX Hype - Some things to think about" in 2005 (while outdated it still has a grain of truth), Rick Stahl writes about the reasons why AJAX should not be the answer to every prayer.

  1. "Grafting AJAX onto existing applications adds another layer of complexity to your application”
  2. "With AJAX, the client code gets large very quickly".
  3. "You should also consider what impact AJAX has on your application’s scalability. AJAX tends to increase the number of requests on a back end application considerably."

ASP .NET AJAX does not offer a fix in every situation for everyone either. ASP.NET AJAX, formerly code-named Atlas, is a set of extensions to ASP.NET developed by Microsoft for implementing Ajax functionality, including both client-side and server-side components.

There are scenarios where AJAX offers the only acceptable solution. That is when server data retrieval is needed and a whole-page refreshing to be avoided. However in other common-place scenarios, such as show and hide a page section based on user input, zoom in and out of an image in responding to a user's mouse movement, AJAX should not be rushed in an ASP .NET page as the rescue. Client-side only reactions should be left to client-side only scripts.

And there is a whole world of JavaScript for us to take advantage of.

So let's jam with ASP .NET and JavaScript code with examples. To demonstrate how we can take advantage of the tons of snappy JavaScript that is out there, I downloaded most of the script for my examples (JavaScript source for this article is mostly from Dynamic Drive DHTML).

Check out the live demo for this article here.

Greybox with ASP .NET server controls

One rule of thumbs of website design is to try to keep the number of pop up windows to a minimum (normal pop-up windows using window.open() call may not work anyway because of the prevalence of popup blockers), another one is try not to have (too many) links away, i.e., links to external websites channeling away traffic.

There have been some work-around scripts for creating non-intrusive and within-site navigation popup. ASP .NET AJAX ModalPopup is one way to do it in ASP .NET Ajax. However, I much prefer the Greybox created by Orangoo Labs. Greybox can have wide use ranging from login, small gallery and external-web page links, etc.

The installation is very easy and business-as-usual; you can simply download and stick the JavaScript references in the head section of a page.

Turns out that installing a Greybox for use with an ASP .NET page is very simple.

The following example, slightly modified from the original example, attaches to GreyBox to a server-side button and a hyperlink.

Step 1: Reference the Greybox JavaScript source in your header section, as instructed in the original JavaScript.

Listing 1: Step 1: Reference the Greybox JavaScript

Step 2: Invoke the GreyBox with a server control, such as a button, a hyperlink, an image, etc. The slight difference is that instead of directly calling the JavaScript function as we would with an HTML input control; we attach it to a server control in the Page_load event by using attributes.add in the code behind page. Please note that GreyBox heavily utilizes the rel attribute of a link tag.

The following example launches a small image gallery on button click and then launches the DotNetSlackers website upon a click of the hyperlink.

Listing 2: The Web Form with a button and a hyperlink

Listing 3: Code Behind

Figure 1: Screenshot of Greybox with server controls

Screenshot of Greybox with server controls

Check out the demo for the code in action.

JavaScript with List controls and how to show/hide a layer

ASP .NET list controls include RadioButtonList, CheckBoxList, DropDownList and ListBox. In the ASP .NET 1.x times, it was a known bug that the regular attributes.add (key, function) didn’t work for list controls. For example, you cannot apply special CSS styles to a particular checkbox if it is checked; and you cannot attach a JavaScript function to a RadioButtoList’s OnClick event. To make your list controls have individual ListItem specific reactions or behaviors, you have to write custom Web Controls inheriting from ListControl. It is not exactly a trivial task (To read more, please see List Control Items and Attributes).

Luckily, we have ASP .NET 2.0 which has swept away bugs like this. However, how do we style different list items? How do we set up JavaScript functions in response to client-side actions, for example, in a common scenario where you want to display a set of questions only if a user has answered "Yes" to a screening question?

We can dress individual List Items in the code-behind page, since it is not possible to set the style declaratively. For example, the following code sets the background color of each list item of a DropdownList of colors.

To toggle the visibility of a specific set, we can do it server-centric way or client-centric way. For the former, you can put the set in a server-side panel, set the list control's autopostback to True, and set the property visible to either False or True. To avoid the annoying whole-page refreshing and unpleasant post back flash, you can also use an UpdatePanel.

The following example is directly plucked out of a survey. It displays the Government-related question if a user indicates that she/he works for Government or Civic agency, or the "other" textbox to allow user to specify the type of work he/she works on.

Listing 4: Using UpdatePanel to show/hide a specific set of questions based on users’ response

In the code behind page, you can define your q1_SelectedIndexChanged function as such:

The above would work.

However, we can do it in a simpler, client-centric way, instead of posting back every user mouse movement to server. First, to each ListItem we add an OnClick attribute; then, rather than wrap the selective set of questions in a server-side control and further wrap it up in UpdatePanel/ContentTemplate tags, we use a client-side layer and adjust its style.display property to either block or none.

For example, we can always rewrite the above server code as follows:

Listing 5: Add JavaScript to server list controls to turn off/on a set of specific questions based on user’s response

Listing 6: JavaScript function to show/hide a layer

In the code behind page, we can do the attributes.add(). Since there are two layers involved in the example, we call the same JavaScript function twice with different parameters.

Listing 7: Add JavaScript function calls to individual ListItem

In the before-mentioned article, Scott Mitchell presents an example of a custom CheckboxList control which contains two sets of exclusive checkboxes. For example, a checkbox that says "None of the above" would cause all of the others be unchecked. That was in the pre-2.0 days.

Now let's try to change the logic a little bit. Let’s use a RadioButtonList to check or uncheck all of the checkbox items in a CheckBoxList, which is also a very common scenario.

Insert the following JavaScript function in the web form.

Listing 8: JavaScript: Check or uncheck all of the items in the checkboxList

Listing 9: The web form with a RadioButtonList and a CheckBoxList

Listing 10: Call the JavaScript from code-behind

Please note that the client function for check/uncheck all the items in a CheckBoxList takes three parameters: sender, the object that evokes the function; checklistName, the collective name or the prefix of the array of checkboxes in concern; total: the total number of checkboxes in the list.

On the server side, we pass the this keyword to refer to the sender itself; the ClientID of the CheckboxList as ChecklistName; and items.count for the total number of checkboxes.

Popup in a GridView

Popup is the darling of web programmers; we always try to outsmart popup-blockers. Good popup are non-intrusive, informative, nimble and visually appealing. Popup are as popular as GridView is powerful. How then to allow a little popup bubbling up while you mouse over each data item of a GridView? I have seen examples using AJAX for GridView popup. However, I doubt it is absolutely necessary.

How about using one of the pop up JavaScript out there and combine it with our powerful and data-rich GridView?

The result is the following:

Figure 2: Screenshot of information popup with a GridView

Screenshot of information popup with 

a GridView

Here is how:

First, download the JavaScript file (tooltip.js in the sample code) and reference it in your ASP .NET page;

Second, set up your Gridview. In my example, I created a dummy DataTable as the Gridview's DataSource (I’ve stripped out the database part to make it simpler);

Third, use attribute.add() to add a note to OnRowCreated event the of Gridview to call the JavaScript function whenever a mouse is detected hovering over the magnifier image, to pop up a small information box.

Listing 11: Code for the OnRowCreated event

To the GridView pop up in action, check out the demo here.

Custom Validation with JavaScript

All the ASP .NET built-in validators - RequiredFieldValidator, CompareValidator, RangeValidator and RegularExpressionValidator are provided with JavaScript as default. You have to set the EnableClientScript property of the validator or ValidationSummary control to False to disable client script validation.

For validations that require special logic - for example, a control's input that needs to check against the input of multiple other controls - the CustomValidator class comes into play. CustomValidator allows us to do validation both on the server and client side, and it is a common practice to place identical validation functions on both sides (I do not know why). Here, we will only focus on the side of client script, since it involves some basics of using the mini-client-side validation API and accessing server controls locally.

Listing 12: A custom validator to validate a group of textboxes to ensure their percentage values add up to 100

Here are some points to note about using CustomValidator:

  • To perform client-side custom validation, we must indicate the name of function in the ClientValidationFunction property. As in the above: ClientValidationFunction="CheckTotal".
  • The custom function must always have the same two parameters: source and arguments (translated on the server-side: customValidate (object sender, EventArgs e)). Source is the client-side CustomValidator object, and arguments is an object with two properties, Value and IsValid. The Value property is the value to be validated and the IsValid property is a Boolean used to set the return result of the validation.
  • In the case where we need to access the value of other server controls, we use document.getElementById ("<%=server control ID.ClientID% >") to access the server control using its ClientID.
  • The IsValid property is false by default. Always explicitly set IsValid property to true if the values are validated.
  • You can leave out the ControlToValidate property. One CustomValidator can be used for a whole web form, in which case, the custom validation function will be fired only once.

Take a look at the Ajax Control Toolkit

"The ASP.NET AJAX Control Toolkit is a joint project between the community and Microsoft that provides a rich array of controls for building interactive Web experiences easily." As of now, the sample website showcases about thirty-four samples of web control extenders, such as Accordion, Animation, AutoComplete.

Extenders are server controls that allow a server control to imitate client-side behaviors. For example, the Accordion allows you to provide multiple panes that can expand or collapse depending on user's mouse click; only one pane will be visible at one time.

If you are not using Visual Studio 2008, or ASP .NET 3.5; to enable extenders to work with web controls, you must first configure your web site to be AJAX enabled, and then you must install the AjaxControlToolkit assembly. Finally, you add the controls to your Toolbox. Then you can drag and drop Toolkit's extenders in your page. It is not very difficult to do, and you do not need to write any JavaScript code to have the benefit of JavaScript, which could be a plus for programmers that do not have any JavaScript skills.

However, in what planet can you develop a rich and fast- responding website with only spoon-fed canned formulas and no JavaScript at all?

To me, the problem with Ajax extenders is that, it is not at all easy to plow through the obtuse process of creating extenders of your own. Given the meager number of extenders available on the sample website and the vast and varied requirement for rich client capabilities, you will soon be out of luck. And think of the world of JavaScript (text effects, image effects, links and menus, mouse and cursors) that are available to download!

Among the extenders in the Ajax Control Toolkit, the auto-complete extender is a good and necessary one, because to provide a list of suggested words to aid users filling their content box, it involves retrieving data (sometimes a heavy amount of data) from server upon every keystroke, which client script could not do. However, others, in my view, are not quite so necessary. It is easier still to cherry-pick from the available JavaScript and directly apply to a web control.

Take the CollapsiblePanel for example. Collapse and expand a layer has been a long-standing JavaScript function. A search will quickly turn up many JavaScript for this purpose. So I downloaded one and added the reference in the web form head section - and with a few lines, I got a nice working collapsible panel. No Toolkit’s .dll plug in, no AJAX configuration.

Listing 13: The accordion web form

Code in the code-behind, using attribute.add to call the JavaScript function:

Summary

ASP .NET is no doubt a powerful web development tool. However, transitioning from ASP to the ever more sophisticated ASP .NET does not mean we have to throw away everything we learned - especially not JavaScript. The article showed how we can easily harvest both the power of the ASP .NET and the rich and fast capacity of the vast repertoire of existing JavaScript; and how we can do it without necessarily fall back on Ajax.

Reference

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Xun Ding

Web developer, Data Analyst, GIS Programmer

This author has published 12 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.

You might also be interested in the following related blog posts


Access ASP.NET Server Controls in JavaScript Files read more
Embed JavaScript in Custom ASP.NET Server Controls read more
ASP.NET 4 Beta 2 - New Version, New Docs, New MSDN Site ! read more
How to render the same template on the server and client with minimal redundancy read more
Adding users to a TFS project when youre not on the domain read more
Assembly-Free jQuery in SharePoint Sites Using the SmartTools jQueryLoader read more
IIS Media Services 3.0 read more
Using Seadragon with ASP.NET MVC read more
Ajax Control Toolkit: new controls, bug fixes read more
NEW VERSION Ajax Control Toolkit read more
Top
 
 
 

Discussion


Subject Author Date
placeholder How to call a javascript function from collapsible panel expand/ collapse(Asp .Net) Eliza Sahoo 2/8/2010 8:04 AM
How can i use greybox with Response.Write? Mahmut Koyuncu 3/26/2010 3:57 AM
placeholder Very interesting article Naomi N 6/30/2008 6:30
RE: Very interesting article Sonu Kapoor 6/30/2008 10:41
placeholder RE: RE: Very interesting article Xun Ding 7/1/2008 10:55 AM
Problem is solved Naomi N 7/1/2008 1:13
placeholder Really Useful For Me! Siva Sankari 7/26/2008 6:23 AM
thank you Xun Ding 7/26/2008 9:40 AM
placeholder thanks a lot Melek Ayse 3/11/2009 11:20 AM

Please login to rate or to leave a comment.