Vous êtes sur la page 1sur 115

Change Image Opacity on MouseOver using jQuery

This short article demonstrates how to change the opacity of an image when the user
hovers the mouse over an image. This article is a sample chapter from my EBook called 51
Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter has been modified
a little to publish it as an article.

Note that for demonstration purposes, I have included jQuery and CSS code in the same
page. Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can change the opacity of an image.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Change Image Opacity on Hover</title>
<style type="text/css">
.imgOpa
{
height:250px;
width:250px;
opacity:0.3;
filter:alpha(opacity=30);
}
</style>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>

<script type="text/javascript">
$(function() {
$('.imgOpa').each(function() {
$(this).hover(
function() {
$(this).stop().animate({ opacity: 1.0 }, 800);
},
function() {
$(this).stop().animate({ opacity: 0.3 }, 800);
})
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Hover over an Image to change its Transparency level</h2>
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl="../images/1.jpg" class="imgOpa" />
<asp:Image ID="Image2" runat="server"
ImageUrl="../images/2.jpg" class="imgOpa" />
<asp:Image ID="Image3" runat="server"
ImageUrl="../images/3.jpg" class="imgOpa" />
<asp:Image ID="Image4" runat="server"
ImageUrl="../images/4.jpg" class="imgOpa" />
</div>
</form>
</body>
</html>

In this example, observe that the images have a class attribute ‘imgOpa’. The definition of
the CSS class is as shown here:

.imgOpa
{
height:250px;
width:250px;
opacity:0.3;
filter:alpha(opacity=30);
}

When the images are loaded, they are in a semitransparent state. In Firefox, Chrome and
Safari, we use the opacity:n property for transparency. The opacity value can be from 0.0 -
1.0, where a lower value makes the element more transparent.

In IE 7 and later, we use filter:alpha(opacity=n) property for transparency, where the


opacity value can be from 0-100.

This is how the images appear in a semitransparent when they are loaded:

When the user hovers the mouse over a semitransparent image, we use the jQuery hover()
method to animate the opacity property from 0.3 to 1.0, thereby creating a cool effect on
the images. The code to achieve this effect is shown below:

$(this).hover(
function() {
$(this).stop().animate({ opacity: 1.0 }, 800);
},
function() {
$(this).stop().animate({ opacity: 0.3 }, 800);
})
});

The screenshot shown below shows how the image will appear when the user hovers the
mouse over an image; let us say the first image. The transparency of the image is changed
from 0.3 to 1.0.
See a Live Demo

I hope you found this article useful and I thank you for viewing it. This article was taken
from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which
contains similar recipes that you can use in your applications

Click and Increase the Size of an Image using jQuery

This short article demonstrates how to click and view a larger image when the thumbnail is
clicked on. This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes
with jQuery and ASP.NET Controls. The chapter has been modified a little to publish it as an
article.

Note that for demonstration purposes, I have included jQuery and CSS code in the same
page. Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can view a larger image when an image
is clicked on

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Click and Increase the Size of an Image</title>
<style type="text/css">
.imgthumb
{
height:100px;
width:100px;
}
.imgdiv
{
background-color:White;
margin-left:auto;
margin-right:auto;
padding:10px;
border:solid 1px #c6cfe1;
height:500px;
width:450px;
}
</style>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>

<script type="text/javascript">
$(function() {
$("img.imgthumb").click(function(e) {
var newImg = '<img src='
+ $(this).attr("src") + '></img>';
$('#ladiv')
.html($(newImg)
.animate({ height: '300', width: '450' }, 1500));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="imgdiv">
<h2>Click on the thumbnail to view a large image</h2>
<br />
<asp:Image ID="imgA" class="imgthumb" runat="server"
ImageUrl="../images/1.jpg" />
<asp:Image ID="imgB" class="imgthumb" runat="server"
ImageUrl="../images/2.jpg" />
<asp:Image ID="imgC" class="imgthumb" runat="server"
ImageUrl="../images/3.jpg" />
<asp:Image ID="Image1" class="imgthumb" runat="server"
ImageUrl="../images/4.jpg" />
<hr /><br />
<div id="ladiv"></div>
</div>
</form>
</body>
</html>

This recipe demonstrates how to increase the size of an image when it is clicked. To give it
an Image gallery effect, when a thumbnail is clicked, we create a new image element and
set its source, to the source of the clicked thumbnail.

var newImg = '<img src='


+ $(this).attr("src") + '></img>';

The next and final step is to set the html contents of a div element to the ‘newImg’ variable
and then increase the image size, by animating the height and width of the image.

$('#ladiv')
.html($(newImg)
.animate({ height: '300', width: '450' }, 1500));

When you run the application, click on the thumbnail to see a large version of the image
with animation, as shown below. Additionally, you can also preload the images for better
performance.
See a Live Demo

I hope you found this article useful and I thank you for viewing it. This article was taken
from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which
contains similar recipes that you can use in your applications.

Create an ASP.NET TextBox Watermark Effect using


jQuery

This short article demonstrates how to create a watermark effect on your TextBox and
display instructions to users, without taking up screen space. This article is a sample
chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET
Controls. The chapter has been modified a little to publish it as an article.

Note that for demonstration purposes, I have included jQuery code in the same page.
Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can create a watermark effect on your
TextBox using client-side code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>TextBox WaterMark</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
>
</script>

<style type="text/css">
.water
{
font-family: Tahoma, Arial, sans-serif;
color:gray;
}
</style>

<script type="text/javascript">
$(function() {

$(".water").each(function() {
$tb = $(this);
if ($tb.val() != this.title) {
$tb.removeClass("water");
}
});

$(".water").focus(function() {
$tb = $(this);
if ($tb.val() == this.title) {
$tb.val("");
$tb.removeClass("water");
}
});

$(".water").blur(function() {
$tb = $(this);
if ($.trim($tb.val()) == "") {
$tb.val(this.title);
$tb.addClass("water");
}
});
});

</script>
</head>
<body>
<form id="form1" runat="server">
<div class="smallDiv">
<h2>TextBox Watermark Demonstration</h2> <br />
<asp:TextBox ID="txtFNm" class="water" Text="Type your First Name"
Tooltip="Type your First Name" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtLNm" class="water" Text="Type your Last Name"
Tooltip="Type your Last Name" runat="server"></asp:TextBox>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<br /><br />
Tip: Click on the TextBox to start typing. The watermark
text disappears.
</div>
</form>
</body>
</html>

The code shown above adds the “watermark” behavior to controls marked with the
‘class=water’ attribute. When the user loads the page, a watermarked textbox displays a
message to the user. As soon as the watermarked textbox receives focus and the user types
some text, the watermark goes away. This technique is a great space saver as you can use
it to provide instructions to the user, without using extra controls that take up valuable
space on your form.

The ‘Tooltip’ attribute applied to the textbox is crucial to this example. The ‘Tooltip’ gets
rendered as ‘title’. Observe the code, as we use this ‘title’ property to compare it to the
textbox value and remove the watermark css, when the textbox control gains focus

$(".water").focus(function() {
$tb = $(this);
if ($tb.val() == this.title) {
$tb.val("");
$tb.removeClass("water");
}
});

Similarly when the user moves focus to a different control without entering a value in the
textbox, we add the watermark css again.

$(".water").blur(function() {
$tb = $(this);
if ($.trim($tb.val()) == "") {
$tb.val(this.title);
$tb.addClass("water");
}
});

The water class declared in Demos.css looks like this:


.water
{
font-family: Tahoma, Arial, sans-serif;
font-size:75%;
color:gray;
}

When the page loads for the first time, the watermark is visible as shown here:

When the user enters the First/Last Name and submits the form, the watermark behavior is
no more needed to be displayed. This is achieved by comparing the ‘title’ with the ‘value’ of
the textbox. If the ‘value’ does not match the ‘title’, this indicates that the user has entered
some value in the textboxes and submitted the form. So in this case we remove the
watermark appearance.

$(".water").each(function() {
$tb = $(this);
if ($tb.val() != this.title) {
$tb.removeClass("water");
}
});

After the user enters the details and submits the form, the result is similar to the one shown
here, without the watermark:

Thanks to Arnold Matusz for sharing the tip about the tooltip property. The code has been
tested on IE 7, IE 8, Firefox 3, Chrome 2, Safari 4 browsers

You can see a Live Demo over here

I hope you found this article useful and I thank you for viewing it. This article was taken
from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which
contains similar recipes that you can use in your applications.
Extending jQuery and Writing Custom Logging for Your
Application in JavaScript

When you work with jQuery allot, you realise how easy it is to get carried away with coding,
and by the time you look up from your keyboard, you’ve created tonnes of code! A nice way
to log data when you’re working with JavaScript is to log data to the console object in Firefox if
you have Firebug installed. Hopefully you’re using Firebug! It’s a valuable development
tool. Firebug adds a global variable named "console" to all web pages loaded in Firefox. The
console window is also available in Google Chrome. The console object contains methods that
allow you to write to the console to expose information that is flowing through your
scripts. The end result is you’ll be able to log data by using the following statement:

jQuery.log([your message]);

For this example you don’t to create a Visual Studio project. A simple HTML file will do.

The console object is available in Firefox and Google Chrome, so for this to be compatible
with other browsers such as Internet Explorer, I’ll write the debug information straight to
the window. Okay let’s get started! Writing to the console object is simple. You write the
following line of code to log data:

console.log(“Hello world!”)

The code above is nice and simple! Next I’m going to extend jQuery and create a custom
function that I can call from anywhere in my code. To extend jQuery you use the
jQuery.extend function. Here’s the complete code below:

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


<head>
<title>jQuery</title>
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var debug = true;
jQuery.extend({
log: function(msg) {
if (debug) {
if (window.console) {
// Firefox & Google Chrome
console.log(msg);
}
else {
// Other browsers
$("body").append("<div
style=\"width:600px;color:#FFFFFF;background-color:#000000;\">" + msg +
"</div>");
}
return true;
}
}
});

$(function() {
$("#Button1").bind("click", function(e) {
jQuery.log("Hello");
e.preventDefault();
});
});
</script>
</head>
<body>
<input id="Button1" type="button" value="button" />
</body>
</html>

In the code above I have first created a variable that will enable/disable logging data:

var debug = true;

To extend jQuery, I am using jQuery’s extend function. I check if the console object is
available. If it is, I call console.log to log the data. If it’s not, then I simply append a new
<div> tag at the end of the <body> tag to print the data.

jQuery.extend({
log: function(msg) {
if (debug) {
if (window.console) {
// Firefox only
console.log(msg);
}
else {
// Other browsers
$("body").append("<div
style=\"width:600px;color:#FFFFFF;background-color:#000000;\">" + msg +
"</div>");
}
return true;
}
}
});

If you run the example and click the button in Firefox, you can open Firebug and see the
data being logged to the console window:
If you run the page using Internet Explorer, the console object is not available, so the data
will be printed in the window:

Hopefully you find this small piece of code useful. It certainly has helped me out recently
whilst trying to debug hard to find issues in JavaScript. See a Live Demo here.

If you liked the article, Subscribe to the RSS Feed or Subscribe Via Email

Malcolm Sheridan is an independent contractor who has been working with Microsoft
technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly
enjoys ASP.NET.
Renaming jQuery UI Tabs

Earlier this year I wrote an article on jQuery Tabs and Lazy Loading. I had some good feedback
about that article which is always nice. Recently I was faced with a different problem when
using jQuery’s tabs. The user wanted the ability to change the headings of any tab through
the browser. The solution is quite straight forward so I thought I’d share it with you in case
you ever needed to do this too.

Before we get started, this example uses the latest version of jQuery which is 1.3.2. That
can be downloaded from here. You’ll also need the jQuery UI Core Tabs Widget and the
Tabs CSS files which can be downloaded from here.

Open Visual Studio 2008 and create a new Web Application. Open the HTML designer and
add the following JavaScript and CSS file references to the <head> HTML tag:

<link type="text/css" href="CSS/jquery-ui-1.7.2.custom.css" rel="stylesheet"


/>
<script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui-
1.7.2.custom.min.js"></script>

The next step is to add the HTML for the tabs:

<div id="tabs">
<ul>
<li><a href="#tabs-0">Nunc tincidunt</a><img
src="Images/x_normal.gif" alt="Rename" /></li>
<li><a href="#tabs-1">Proin dolor</a><img
src="Images/x_normal.gif" alt="Rename" /></li>
</ul>
<div id="tabs-0">
Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur
nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam
ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor
risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend
adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla.
Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut
dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus
lectus.
</div>
<div id="tabs-1">
Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut
pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed
fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus
eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in
ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing
adipiscing. Morbi facilisis. Curabitur ornare consequat nunc.
Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat.
Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium
posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris
consectetur tortor et purus.
</div>
</div>
In the HTML above, the <a> tag in the <ul> tag will be rendered as the tab. After each
<a> tag there’s an image that the user can click on to rename the tab. I wanted to create a
generic piece of JavaScript that will rename any tab the user wants to rename. Add the
following JavaScript code to the <head> section:

<script type="text/javascript">
$(function() {
// Tabs
$('#tabs').tabs({
selected: -1
});

//hover states on the static widgets


$('#dialog_link, ul#icons li').hover(
function() { $(this).addClass('ui-state-
hover'); },
function() { $(this).removeClass('ui-state-
hover'); }
);

$("img[alt=Rename]").click(function(e) {
var reply = prompt("Type in a name for the tab");
if (reply != null && reply.trim().length > 0) {
$(e.target).prev("a").text(reply);
}
});
});
</script>

In the code above, the magic piece of code that allows the user to rename a tab is this:

$("img[alt=Rename]").click(function(e) {
var reply = prompt("Type in a name for the tab");
if (reply != null && reply.trim().length > 0) {
$(e.target).prev("a").text(reply);
}
});

When the page loads, jQuery will bind the click event to any image that has a Rename alt
attribute. That will allow me to target only those images on the page. When the user clicks
on any image, a JavaScript prompt will be displayed asking the user for some information:

If the user types in some text, the next task is to locate the tab to rename. The event object
is guaranteed to be passed to the event handler. The target property contains the DOM
element that issued the event. Once we know the image that was clicked, we then need to
find the previous <a> tag so the text can be updated. This is achieved using the prev
method in jQuery. This returns a set of elements containing the unique previous siblings of
each of the matched set of elements. Finally the text is updated using the text method:

When the user clicks OK the text will be updated:

A simple solution in the end! I hope you enjoyed reading this article. The entire source
code of this article can be downloaded over here

Synchronize Scrolling of Two Multiline TextBoxes using


jQuery

This short article demonstrates how to synchronize scrolling of two ASP.NET Multiline
TextBoxes using jQuery. This article is a sample chapter from my EBook called 51 Tips,
Tricks and Recipes with jQuery and ASP.NET Controls.

Note that for demonstration purposes, I have included jQuery code in the same page.
Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can synchronize scrolling of two
ASP.NET MultilineTextBoxes by using minimum client-side code

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sync two Multiline TextBoxes</title>
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

<script type="text/javascript">
$(function() {
var $tb1 = $('textarea[id$=tb1]');
var $tb2 = $('textarea[id$=tb2]');
$tb1.scroll(function() {
$tb2.scrollTop($tb1.scrollTop());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="bigDiv">
<h2>Click and scroll in the left textbox to see the
synchronized scroll in right textbox</h2><br /><br />
<asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"
Text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum"
Tooltip="Click on scrollbar to see the scroll on right box"
Rows="5"/>
<asp:TextBox ID="tb2" runat="server" TextMode="MultiLine"
Text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum"
Rows="5"/>
<br /><br />
Tip: Scrolling the right textbox does not affect the left one.
</div>
</form>
</body>
</html>

The technique shown above synchronizes the scrolling of TextBox (tb2) with TextBox (tb1).
As the user scrolls through the contents of tb1, tb2 automatically scrolls to keep up with the
display of tb1.

$tb1.scroll(function() {
$tb2.scrollTop($tb1.scrollTop());
});

As shown in the screenshot below, after scrolling 4 lines of the first textbox, the second
textbox scrolls automatically to keep up with the first textbox scrolling:
This example is well suited for a requirement when two versions of the same document are
to be compared with each other and the user need not have to explicitly scroll through both
the versions to compare them.

Note: The code works when the user scrolls using the keyboard or mouse and has been
tested on IE 7, IE 8, Firefox 3, Chrome 2, Safari 4 browsers

You can see a Live Demo over here.

I hope you found this article useful and I thank you for viewing it. This article was taken
from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which
contains similar recipes that you can use in your applications.

Cascading DropDownLists With ASP.NET and jQuery

Cascading drop down lists is a really nice feature for web developers. I thought it was time
to write an article on how to do this using ASP.NET and jQuery. Well here’s one way of
doing it. Before we get started, this example uses the latest version of jQuery which is
1.3.2. That can be downloaded from here.

Open Visual Studio 2008 and create a new Web Application. For this article I’m not going to
connect to a database. I’ve created two classes, Employee and EmployeeCars, which will
store the data. Create two new classes and add the following code:

C#

public class Employee


{
public int Id { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }

public List<Employee> FetchEmployees()


{
return new List<Employee>
{
new Employee {Id = 1, GivenName = "Tom", Surname =
"Hanks"},
new Employee {Id = 2, GivenName = "Tiger", Surname
= "Woods"},
new Employee {Id = 3, GivenName = "Pat", Surname =
"Cash"}
};
}

public Employee FetchEmployee(int id)


{
var employees = FetchEmployees();
return (from p in employees
where p.Id == id
select p).First();
}
}

public class EmployeeCar


{
public int Id { get; set; }
public string Car { get; set; }

private static List<EmployeeCar> LoadData()


{
return new List<EmployeeCar>
{
new EmployeeCar {Id = 1, Car = "Ford"},
new EmployeeCar {Id = 1, Car = "Holden"},
new EmployeeCar {Id = 1, Car = "Honda"},
new EmployeeCar {Id = 2, Car = "Toyota"},
new EmployeeCar {Id = 2, Car = "General Motors"},
new EmployeeCar {Id = 2, Car = "Volvo"},
new EmployeeCar {Id = 3, Car = "Ferrari"},
new EmployeeCar {Id = 3, Car = "Porsche"},
new EmployeeCar {Id = 3, Car = "Ford"}
};
}

public List<EmployeeCar> FetchEmployeeCars(int id)


{
return (from p in LoadData()
where p.Id == id
select p).ToList();
}
}

VB.NET

Public Class Employee


Private privateId As Integer
Public Property Id() As Integer
Get
Return privateId
End Get
Set(ByVal value As Integer)
privateId = value
End Set
End Property
Private privateGivenName As String
Public Property GivenName() As String
Get
Return privateGivenName
End Get
Set(ByVal value As String)
privateGivenName = value
End Set
End Property
Private privateSurname As String
Public Property Surname() As String
Get
Return privateSurname
End Get
Set(ByVal value As String)
privateSurname = value
End Set
End Property

Public Function FetchEmployees() As List(Of Employee)


Return New List(Of Employee)
Dim Employee As New
"Tom", Surname = "Hanks"
1, GivenName = "Tom", Surname
Id = 1, GivenName
, New Employee
"Tiger", Surname = "Woods"
2, GivenName = "Tiger", Surname
Id = 2, GivenName
, New Employee
"Pat", Surname = "Cash"}
3, GivenName = "Pat", Surname
Id = 3, GivenName

public Employee FetchEmployee(Integer id)


Dim employees = FetchEmployees()
Return ( _
From p In employees _
Where p.Id = id _
Select p).First()
End Function

Public Class EmployeeCar


Private privateId As Integer
Public Property Id() As Integer
Get
Return privateId
End Get
Set(ByVal value As Integer)
privateId = value
End Set
End Property
Private privateCar As String
Public Property Car() As String
Get
Return privateCar
End Get
Set(ByVal value As String)
privateCar = value
End Set
End Property

Private Shared Function LoadData() As List(Of EmployeeCar)


Return New List(Of EmployeeCar)
Dim EmployeeCar As New
1, Car = "Ford"
Id = 1, Car
, New EmployeeCar
1, Car = "Holden"
Id = 1, Car
, New EmployeeCar
1, Car = "Honda"
Id = 1, Car
, New EmployeeCar
2, Car = "Toyota"
Id = 2, Car
, New EmployeeCar
2, Car = "General Motors"
Id = 2, Car
, New EmployeeCar
2, Car = "Volvo"
Id = 2, Car
, New EmployeeCar
3, Car = "Ferrari"
Id = 3, Car
, New EmployeeCar
3, Car = "Porsche"
Id = 3, Car
, New EmployeeCar
3, Car = "Ford"}
Id = 3, Car

public List(Of EmployeeCar) FetchEmployeeCars(Integer id)


Return ( _
From p In LoadData() _
Where p.Id = id _
Select p).ToList()
End Function

That’s all the work to store the data. The next step is to open the Default.aspx code
behind. I need to add code to the page load event to fill the drop down list with the
employees. I’ll also need a method that can be called through jQuery to update the
employee’s cars when the user changes the selected employee. Add the following code to
the Default.aspx.cs page:

C#

[WebMethod]
public static List<EmployeeCar> FetchEmployeeCars(int id)
{
var emp = new EmployeeCar();
return emp.FetchEmployeeCars(id);
}

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
var employees = new Employee();
ddlEmployee.DataSource = employees.FetchEmployees();
ddlEmployee.DataTextField = "Surname";
ddlEmployee.DataValueField = "Id";
ddlEmployee.DataBind();
}
}

VB.NET

<WebMethod> _
Public Shared Function FetchEmployeeCars(ByVal id As Integer) As List(Of
EmployeeCar)
Dim emp = New EmployeeCar()
Return emp.FetchEmployeeCars(id)
End Function

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


If (Not IsPostBack) Then
Dim employees = New Employee()
ddlEmployee.DataSource = employees.FetchEmployees()
ddlEmployee.DataTextField = "Surname"
ddlEmployee.DataValueField = "Id"
ddlEmployee.DataBind()
End If
End Sub

The FetchEmployeeCars method has been decorated with the WebMethod attribute and it’s
static. This will allow the call from jQuery using the Ajax method. Let’s turn our attention to
the HTML now. To begin with add the following JavaScript to the <head> HTML tag:

<script language="javascript" type="text/javascript"


src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script language="javascript" type="text/javascript">


$(function() {
var $ddl = $("select[name$=ddlEmployee]");
var $ddlCars = $("select[name$=ddlEmployeeCars]");
$ddl.focus();
$ddl.bind("change keyup", function() {
if ($(this).val() != "0") {
loadEmployeeCars($("select
option:selected").val());
$ddlCars.fadeIn("slow");
} else {
$ddlCars.fadeOut("slow");
}
});
});
function loadEmployeeCars(selectedItem) {
$.ajax({
type: "POST",
url: "Default.aspx/FetchEmployeeCars",
data: "{id: " + selectedItem + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function Success(data) {
printEmployeeCars(data.d);
}
});
}

function printEmployeeCars(data) {
$("select[name$=ddlEmployeeCars] > option").remove();
for (var i = 0; i < data.length; i++) {
$("select[name$=ddlEmployeeCars]").append(
$("<option></option>").val(data[i].Id).html(data[i].Car)
);
}
}
</script>

I’ll break down the code above into smaller chunks. When the page loads, the code looks for
the DropDownList named ddlEmployee (I haven’t added that yet):

var $ddl = $("select[name$=ddlEmployee]");

It binds the change & keyup events to a function. These events will be triggered when the user
selects a different employee. If they have selected an employee, the loadEmployeeCars
function will be called. If they choose the default value, (Please Select), the employee cars
drop down list will disappear:

$ddl.bind("change keyup", function() {


if ($(this).val() != "0") {
loadEmployeeCars($("select option:selected").val());
$ddlCars.fadeIn("slow");
} else {
$ddlCars.fadeOut("slow");
}
});

The loadEmployeeCars function accepts the selected employee as an argument. It performs


the Ajax call to the FetchEmployeeCars method.

function loadEmployeeCars(selectedItem) {
$.ajax({
type: "POST",
url: "Default.aspx/FetchEmployeeCars",
data: "{id: " + selectedItem + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function Success(data) {
printEmployeeCars(data.d);
}
});
}

Once the employee’s car details are returned, it passes the data to the printEmployeeCars
function. This function clears the items from the ddlEmployeeCars drop down list, and then
adds the new items to the list:

function printEmployeeCars(data) {
$("select[name$=ddlEmployeeCars] > option").remove();
for (var i = 0; i < data.length; i++) {
$("select[name$=ddlEmployeeCars]").append(
$("<option></option>").val(data[i].Id).html(data[i].Car)
);
}
}

Lastly here’s the drop down lists:

<asp:DropDownList ID="ddlEmployee" runat="server"


AppendDataBoundItems="true">
<asp:ListItem Text="(Please Select)" Value="0" Selected="True" />
</asp:DropDownList>
<asp:DropDownList ID="ddlEmployeeCars" runat="server">
</asp:DropDownList>

If you run the code you’ll see by default there’s only a drop down list containing employees:

Once you select an employee, the employee’s list of cars will be displayed:

This functionality can be used if you have more than two drop down lists. I hope you
enjoyed reading this article. The entire source code of this article can be downloaded over
here

Rotate ASP.NET Hyperlink Controls in the Same Position


using jQuery

This short article demonstrates how to rotate a group of Hyperlink Controls in the same
position using jQuery. This article is a sample chapter from my EBook called 51 Tips,
Tricks and Recipes with jQuery and ASP.NET Controls and has been modified to post it
as an article.
Note that for demonstration purposes, I have included jQuery code in the same page.
Ideally, these resources should be created in separate folders for maintainability.

People who have been monetizing their sites need no introduction to TextLinkAds. In simple
words, Text Link Ads are Hyperlinks sponsored by Advertisers. When a user clicks on these
hyperlinks, they are sent to the sponsor’s website. In this recipe, I will demonstrate how to
rotate multiple hyperlinks or TextLinkAds on the same position.

Let us quickly jump to the solution and see how we can rotate a group of Hyperlink Controls
using client-side code. This example uses the latest minified version of jQuery which is 1.3.2
that can be downloaded from here. This example assumes that you have a folder called
"Scripts" with the jQuery file (jquery-1.3.2.min.js) in that folder

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Timer based toggling of hyperlink</title>
<script type='text/javascript'
src='../Scripts/jquery-1.3.2.min.js'>
</script>

<script type="text/javascript">
$(function() {
var anch = $("a.dev");
$(anch).hide().eq(0).show();
var cnt = anch.length;

setInterval(linkRotate, 3000);

function linkRotate() {
$(anch).eq((anch.length++) % cnt).fadeOut("slow", function() {
$(anch).eq((anch.length) % cnt)
.fadeIn("slow");
});
}
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div class="tableDiv">
<h2>The Hyperlink and Text shown below changes after 3 seconds
</h2><br />
<asp:HyperLink ID="linkA" runat="server" class="dev"
NavigateUrl="http://www.dotnetcurry.com">
DotNetCurry</asp:HyperLink>
<asp:HyperLink ID="linkB" runat="server" class="dev"
NavigateUrl="http://www.sqlservercurry.com">
SqlServerCurry</asp:HyperLink>
<asp:HyperLink ID="linkC" runat="server" class="dev"
NavigateUrl="http://www.devcurry.com">
DevCurry</asp:HyperLink>
</div>
</form>
</body>
</html>
We begin by hiding all the hyperlinks with class="dev" and then display the first one.

var anch = $("a.dev");


$(anch).hide().eq(0).show();

We then use the JavaScript setInterval() function to delay the execution of a function
(linkRotate) for a specific time, in our case 3000 millisecond (3 seconds), as shown below:

setInterval(linkRotate, 3000);

The advantage of the setInterval() function is that it continues to repeat the process of
triggering the function at the specified interval, thereby giving it a loop effect.

In the linkRotate() function, we use a simple expression (anch.length++) % cnt that


calculates the index to be supplied to the eq() selector and applies the fadeout/fadeIn()
animations on the current hyperlink. eq(0) refers to the first link, eq(1) to the second link
and so on.

function linkRotate() {
$(anch).eq((anch.length++) % cnt).fadeOut("slow", function() {
$(anch).eq((anch.length) % cnt)
.fadeIn("slow");
});
}

The chart shown below helps you understand what happens at every loop

Loop Number Value of anch.length Value of (anch.length++) % cnt


1 3 3mod3 = 0
2 4 4mod3 = 1
3 5 5mod3 = 2
4 6 6mod3=0
and so on….

You can see a Live Demo

I hope you found this article useful and I thank you for viewing it. This article was taken
from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET
Controlswhich contains similar recipes that you can use in your applications.

Sort the Items of an ASP.NET DropDownList using


jQuery

This short article demonstrates how to sort the items of an ASP.NET DropDownList using
jQuery. This article is a sample chapter from my EBook called 51 Tips, Tricks and Recipes
with jQuery and ASP.NET Controls and has been modified to post it as an article.

Note that for demonstration purposes, I have included jQuery code in the same page.
Ideally, these resources should be created in separate folders for maintainability.
Let us quickly jump to the solution and see how we can sort the items of an ASP.NET
DropDownList using client-side code. This example uses the latest minified version of jQuery
which is 1.3.2 that can be downloaded from here. This example assumes that you have a
folder called "Scripts" with the jQuery file (jquery-1.3.2.min.js) in that folder.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sort Items of an ASP.NET DropDownList</title>
<script src='../Scripts/jquery-1.3.2.min.js'
type='text/javascript'>
</script>

<script type="text/javascript">
$(function() {
$('input[id$=btnSort]').click(function(e) {
e.preventDefault();
var sortedDdl =
$.makeArray($('select[id$=DDL] option'))
.sort(function(o, n) {
return $(o).text() < $(n).text() ? -1 : 1;
});
$("select[id$=DDL]").html(sortedDdl).val("1");
$("#para").html("Items were Sorted!");
$(this).attr("disabled", "disabled");
});
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div class="smallDiv">
<h2>Click on the Sort Button to Sort the DropDownList </h2>
<asp:DropDownList ID="DDL" runat="server" >
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item4" Value="4"></asp:ListItem>
<asp:ListItem Text="Item5" Value="5"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:Button ID="btnSort" runat="server" Text="Sort" />
<p id="para"></p>
<br /><br />
Tip: Items are sorted in an Ascending order
</div>
<br /><br /><br /><br /><br /><br />
<div id="divDemo" class="w2">
This demo is from my EBook
<a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=403">51 Tips,
Tricks and Recipes using jQuery and ASP.NET Controls
</a>
<br /><br />
Visit <a
href="http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=63">DotNetCurry</a
> and
<a href="http://www.devcurry.com/search/label/jQuery">DevCurry</a> for
more tips and tricks on jQuery
and ASP.NET
</div>
</form>
</body>
</html>
In the code shown above, when the user clicks on the Sort button, the <option> elements
are converted to an array using $.makeArray().

$.makeArray($('select[id$=DDL] option'))

The JavaScript built-in sort() function is used on this array, which does an in-place sort of
the array.

$.makeArray($('select[id$=DDL] option'))
.sort(function(o, n) {
return $(o).text() < $(n).text() ? -1 : 1;
});

The final step is to empty the contents of the DropDownList and then use the .html() to
replace the existing <options> with the sorted <options>.

$("select[id$=DDL]").empty().html(sorted)

The val("1") sets the first option as selected, after the sorting has been done.

When the page loads, the output looks similar to the following screenshot:

Before clicking on the Sort button, the output is as shown below:

After clicking on the Sort Button, the output is as shown below:


Tip: To sort in a descending order, replace this line

$(a).text() < $(b).text()

with this:

$(a).text() > $(b).text()

You can see a Live Demo over here.

I hope you found this article useful and I thank you for viewing it. This article was taken
from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which
contains similar recipes that you can use in your applications.

Use Keyboard Shortcuts to Create Tooltips for Forms


using jQuery

I’ve said this once and I’ll say it again, jQuery is cool. Something on the web that is very
helpful to users when filling out HTML forms is for you, the developer, to give them help
along the way. I thought it would be cool to use jQuery to show help tooltips when the user
clicks on a combination of keys using their keyboard. This article will demonstrate how to
capture keyboard events in JavaScript and display help tooltips.

Before we get started, this example uses the latest version of jQuery which is 1.3.2. That
can be downloaded from here. The jQuery Tools and can be downloaded from here.

Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application. Add
the following HTML to the Default.aspx page:

<table>
<tr>
<td>
Given Name
</td>
<td>
<input type="text" maxlength="10" id="txtGivenName" />
</td>
<td>
<div id="givenName" style="display:none;" title="G">
<img src="info.png" alt="Info" width="16" height="16"
/>
Please supply your given name</div>
</td>
</tr>
<tr>
<td>
Surname
</td>
<td>
<input type="text" maxlength="20" id="txtSurname" />
</td>
<td>
<div id="surname" style="display:none;" title="S">
<img src="info.png" alt="Info" width="16" height="16"
/>
Please supply your surname. This can only be
<b>20</b> characters long</div>
</td>
</tr>
</table>

The HTML above is quite simple. There’s a table which contains two text boxes. In the cell to
the right of the text boxes there’s a <div> element which contains an image and some
useful text if the user gets lost or in unsure of what value to put in the text box. To make a
generic piece of JavaScript I’m going to use the title attribute in the <div> element. I’ll use
that as the key to combine with the shift key. The next step is to add the following jQuery
code to the <head> section of the page. Ideally JavaScript should go to a separate .js file,
however for this example; I’ll keep it in the same page:

<script language="javascript" type="text/javascript"


src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></scrip
t>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(this).keydown(function(e) {
var evt = e || window.event;
if (evt.shiftKey) {
findHelp(evt).fadeIn("slow");
}
});

$(this).keyup(function(e) {
var evt = e || window.event;
if (evt.shiftKey) {
findHelp(evt).hide("fast");
}
});
});

function findHelp(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
return $("div[title=" + String.fromCharCode(key) + "]");
}
</script>
In the above code, I’m binding to the document’s keydown and keyup events. On the
keydown event, I want to show the tooltip, and on keyup, hide it.

$(this).keydown(function(e)

$(this).keyup(function(e)

Both pieces of code get information about the event through the argument e. Because I only
want this to work when the user holds down the shift key, I’m checking for that through the
evt.shiftKey variable. This indicates whether the shift key was pressed when the event fired

var evt = e || window.event;


if (evt.shiftKey)

From there I have created a function called findHelp. The sender of the event is passed to
this function. I grab either the keyCode or charCode value, and then use that in the jQuery
Selector to find the related <div> element by its title attribute:

function findHelp(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
return $("div[title=" + String.fromCharCode(key) + "]");
}

Running this code now will display the simple form. If you hold down Shift + S or Shift + G
it will show and hide the tooltip for each text box.

Before the keydown event and on the keyup event

During the keydown event

This is a nice addition for any website that wants to help their users fill out HTML forms. For
more information on keyboard events you can go here for more reading. The entire source
code of this article can be downloaded over here

Implementing KeyBoard Shortcuts on an ASP.NET


Hyperlink Control using jQuery
Popular Web apps like Gmail and Windows Live Mail feature Keyboard shortcuts, which help
you save time by executing common operations using the Keyboard, without having to
switch between the keyboard and mouse. In this short article, I will demonstrate how to use
jQuery to implement keyboard shortcuts on an ASP.NET Hyperlink control. This article is a
sample chapter from my EBook called 51 Tips, Tricks and Recipes with jQuery and
ASP.NET Controls

Note that for demonstration purposes, I have included jQuery code in the same page.
Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can implement KeyBoard shortcut on
the Hyperlink control

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Implement KeyBoard Shortcuts on Hyperlinks</title>
<script type='text/javascript'
src='../Scripts/jquery-1.3.2.min.js'>
</script>

<script type="text/javascript">
$(function() {
$(document).keyup(function(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
switch (key) {
case 49:
navigateUrl($('a[id$=linkA]'));
break;
case 50:
navigateUrl($('a[id$=linkB]'));
break;
case 51:
navigateUrl($('a[id$=linkC]'));
break;
default: ;
}
});
function navigateUrl(jObj) {
window.location.href = $(jObj).attr("href");
alert("Navigating to " + $(jObj).attr("href"));
}
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div class="tableDiv">
<h2>Use Keyboard Keys 1, 2 or 3 to invoke respective
websites</h2><br />
<asp:HyperLink ID="linkA" runat="server"
NavigateUrl="http://www.dotnetcurry.com">
DotNetCurry</asp:HyperLink><br /><br />
<asp:HyperLink ID="linkB" runat="server"
NavigateUrl="http://www.sqlservercurry.com">
SqlServerCurry</asp:HyperLink><br /><br />
<asp:HyperLink ID="linkC" runat="server"
NavigateUrl="http://www.devcurry.com">
DevCurry</asp:HyperLink><br /><br />
</div>

</form>
</body>
</html>

Implementing a Keyboard shortcut in jQuery is relatively simple as shown here. The code
first captures the keyup event and the key is detected using the keyCode or charCode.

$(document).keyup(function(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);

In the code shown below, if the key = 49, digit 1 is pressed by the user and the first
Hyperlink is auto-clicked. Similarly if the key = 50 or 51, then digit 2 or 3 are pressed
respectively and the 2nd or 3rd hyperlink is autoclicked. Once the key matches any of the
switch case statement, the function navigateUrl() is called passing in the respective
hyperlink control object to the function. So if the user pressed 1, the first hyperlink control
object is passed to the function as shown below:

switch (key) {
case 49:
navigateUrl($('a[id$=linkA]'));
break;

The navigateUrl function looks like this:

function navigateUrl(jObj) {
window.location.href = $(jObj).attr("href");
}

The function accepts the hyperlink object and sets the ‘window.location.href’ to the href
attribute of the Hyperlink passed in. This is how we invoke actions with shortcut keys.

Tip: keyCode represents the actual key pressed as a numerical value, whereas charCode
gives the ASCII/Unicode value of the key press result (for eg: Shift + A). Firefox and other
browsers also support ‘e.which’. IE and Opera does not support charCode.

Keyboard shortcuts improve productivity by accomplishing tasks more quickly and without
much effort. In applications, where the user has to select from a variety of actions to
perform, keyboard shortcuts can save on time and effort.

You can see a Live Demo over here. The entire source code of this article can be
downloaded over here

I hope you found this article useful and I thank you for viewing it. This article was taken
from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which
contains similar recipes that you can use in your applications.

Search and Filter Items of an ASP.NET DropDownList


using jQuery
In this short article, I will demonstrate how to search and filter items of an ASP.NET
DropDownList using jQuery. This article is a sample chapter from my EBook called 51 Tips,
Tricks and Recipes with jQuery and ASP.NET Controls.

Note that for demonstration purposes, I have included jQuery code in the same page.
Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can search and filter items of a
DropDownList

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Search and Filter a DropDownList</title>
<script src="Scripts/jquery-1.3.2.min.js"
type="text/javascript"></script>

<script type="text/javascript">
$(function() {
var $txt = $('input[id$=txtNew]');
var $ddl = $('select[id$=DDL]');
var $items = $('select[id$=DDL] option');

$txt.keyup(function() {
searchDdl($txt.val());
});

function searchDdl(item) {
$ddl.empty();
var exp = new RegExp(item, "i");
var arr = $.grep($items,
function(n) {
return exp.test($(n).text());
});

if (arr.length > 0) {
countItemsFound(arr.length);
$.each(arr, function() {
$ddl.append(this);
$ddl.get(0).selectedIndex = 0;
}
);
}
else {
countItemsFound(arr.length);
$ddl.append("<option>No Items Found</option>");
}
}

function countItemsFound(num) {
$("#para").empty();
if ($txt.val().length) {
$("#para").html(num + " items found");
}

}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Enter Text in the TextBox to Filter the DropDownList </h2>
<br />
<asp:TextBox ID="txtNew" runat="server"
ToolTip="Enter Text Here"></asp:TextBox><br />
<asp:DropDownList ID="DDL" runat="server" >
<asp:ListItem Text="Apple" Value="1"></asp:ListItem>
<asp:ListItem Text="Orange" Value="2"></asp:ListItem>
<asp:ListItem Text="Peache" Value="3"></asp:ListItem>
<asp:ListItem Text="Banana" Value="4"></asp:ListItem>
<asp:ListItem Text="Melon" Value="5"></asp:ListItem>
<asp:ListItem Text="Lemon" Value="6"></asp:ListItem>
<asp:ListItem Text="Pineapple" Value="7"></asp:ListItem>
<asp:ListItem Text="Pomegranate" Value="8"></asp:ListItem>
<asp:ListItem Text="Mulberry" Value="9"></asp:ListItem>
<asp:ListItem Text="Apricot" Value="10"></asp:ListItem>
<asp:ListItem Text="Cherry" Value="11"></asp:ListItem>
<asp:ListItem Text="Blackberry" Value="12"></asp:ListItem>
</asp:DropDownList>
<br />
<p id="para"></p>
<br /><br />
Tip: Items get filtered as characters are entered in the textbox.
Search is not case-sensitive
</div>

</form>
</body>
</html>

The example starts by caching the following objects into variables

var $txt = $('input[id$=txtNew]');


var $ddl = $('select[id$=DDL]');
var $items = $('select[id$=DDL] option');

On the keyup() event of the textbox, we are calling the searchDdl() method which accepts
the textbox value as its parameter.

$txt.keyup(function() {
searchDdl($txt.val());
});

Inside the searchDdl() method, the contents of the DropDownList are emptied and we then
use the RegExp object to store the search pattern. In this case, the search modifier is ‘i’
which tells the regular expression to ignore the case of the characters. The expression gets
translated to /searchtext/i
Let us analyze this piece of code given below:

var arr = $.grep($items,


function(n) {
return exp.test($(n).text());
});

The $.grep() method finds the elements of an array which satisfy a filter function. The
syntax is as follows:

$.grep( array, callback, [invert] )

where the array refers to the set of <option> elements that are searched, and the callback
refers to the function to process each item against. In this callback function, we call the
.test() method of the RegExp object, passing it the option item text to see if it matches the
characters entered by the user. The .grep() this way returns a newly constructed array
containing a list of matched items, shown in the code above.

If the array contains matched items, the $.each() iterates over this collection(returned by
the $.grep() method) and fires a callback function on each item, which appends the item to
the DropDownList. The number of items that match the search are displayed using
countItemsFound() function.

if (arr.length > 0) {
countItemsFound(arr.length);
$.each(arr, function() {
$ddl.append(this);
$ddl.get(0).selectedIndex = 0;
}
);
}
else {
countItemsFound(arr.length);
$ddl.append("<option>No Items Found</option>");
}

If the search does not match the items in the DropDownList, we display ‘No Items Found’
using the following code:

$ddl.append("<option>No Items Found</option>");

This is how we search and filter through the list.

Before the user type’s text in the TextBox, the output looks similar to the following:
After the user types some text in the TextBox, the output is as shown below:

Tip: If you want to reverse the filter condition, use the [invert] attribute of the $.grep()
method. For e.g. if you want to filter the DropDownList with items that ‘do not match’ the
text entered by the user, use the [invert] attribute as shown below. This attribute takes a
Boolean value.
var arr = $.grep($items,
function(n) {
return exp.test($(n).text());
}, true);

You can see a Live Demo of this article. You can also download the entire source code of
this article from here.
Using jQuery's UI Slider For Page Sizes

Recently I did an article on Efficient Server Side Paging With ASP.NET and jQuery where I
explained how jQuery’s Ajax functionality could be used to eliminate the need to use page
heavy server controls such as the GridView, and prevent bloating your page with tonnes of
ViewState.

I thought it might be an idea to build on this article and incorporate the jQuery UI Slider
widget to give the user the power to change how many records are displayed per page by
sliding the control. The end result will show you how to create a slider to set the number of
rows displayed per page. The end result will look something like this:

Before we get started, this example uses the latest version of jQuery which is 1.3.2. That
can be downloaded from here. You’ll also need the jQuery UI Core Slider Widget and the
Slider’s CSS files which can be downloaded from here. You’ll also need a copy of the
Northwind database. If you don’t have a copy of the Northwind database, you can go here to
download it. Finally you’ll need to download a copy of jTemplates.

The Slider has a number of different options available. Some of the ones I’ll work with in
this article are:

 max – the maximum number of the slider


 min – the minimum number of the slider
 orientation – horizontal or vertical
 value – determines the value of the slider
 step - determines the size or amount of each interval or step the slider takes
between min and max
The two events I’m working with are:

 slide - this event is triggered on every mouse move during slide


 change - this event is triggered on slide stop, or if the value is changed
programmatically (by the value method)

Let’s get started! Open Visual Studio 2008 and create a new Web Application. To begin with
add a new LINQ to SQL Classes file to your project and call it Northwind. Add the customer
table to the design surface:

Save and build your project. Now that is done I’m going to create a custom class to return
to the client. I’m creating it this way because the method needs to return not only a list of
customers, but it also needs to return the total customer count for the paging to function
correctly. Add a new class to your web application and call it CustomerData. Add the
following code:

C#

public class CustomerData


{
public List<Customer> Customers { get; set; }
public int TotalRecords { get; set; }
}

VB.NET

Public Class CustomerData


Private privateCustomers As List(Of Customer)
Public Property Customers() As List(Of Customer)
Get
Return privateCustomers
End Get
Set(ByVal value As List(Of Customer))
privateCustomers = value
End Set
End Property
Private privateTotalRecords As Integer
Public Property TotalRecords() As Integer
Get
Return privateTotalRecords
End Get
Set(ByVal value As Integer)
privateTotalRecords = value
End Set
End Property
End Class

The CustomerData class has two properties. The Customers property will contain the list of
customers, and TotalRecords will hold the total number of records. Now we need to add one
method to the default page to retrieve the data. This needs to be decorated with the
WebMethod attribute so it can be consumed by jQuery’s Ajax function. Add the following
method to fetch the customer data.

C#

[WebMethod]
public static CustomerData FetchCustomers(int skip, int take)
{
var data = new CustomerData();
using (var dc = new NorthwindDataContext())
{
var query = (from p in dc.Customers
select p)
.Skip(skip)
.Take(take)
.ToList();
data.Customers = query;
data.TotalRecords = (from p in dc.Customers
select p).Count();
}
return data;
}

VB.NET

<WebMethod> _
Public Shared Function FetchCustomers(ByVal skip As Integer, ByVal take As
Integer) As CustomerData
Dim data = New CustomerData()
Using dc = New NorthwindDataContext()
Dim query = ( _
From p In dc.Customers _
Select p).Skip(skip).Take(take).ToList()
data.Customers = query
data.TotalRecords = ( _
From p In dc.Customers _
Select p).Count()
End Using
Return data
End Function

In the code above the method acceps two parameters, skip and take which are integer
values that will be used to run the IQueryable Take and Skip methods. These methods create
an SQL statement that only returns records between the rows starting at the Take value,
and then skipping all the rows in the Skip value instead of the whole table. That’s the server
code done! The next step is to add the JavaScript. Open the Default.aspx page and add the
following jQuery code to the <head> section of the page. Ideally JavaScript should go to a
separate .js file, however for this example; I’ll keep it in the same page:

<script language="javascript" type="text/javascript" src="jquery-


1.3.2.js"></script>
<script language="javascript" type="text/javascript" src="jquery-ui-
1.7.2.custom.min.js"></script>
<script language="javascript" type="text/javascript"
src="http://jtemplates.tpython.com/jTemplates/jquery-jtemplates.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var $slide = $("#slider");
$slide.slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 20,
value: 10,
step: 1,
slide: function(event, ui) {
printRecordsPerPage(ui.value);
},
change: function(event, ui) {
fetchCustomer(1);
}
});
printRecordsPerPage($slide.slider("option", "value"));
fetchCustomer(1);
});

function fetchCustomer(skip) {
var $slide = $("#slider");
var take = $slide.slider("option", "value");
var skippy = skip == 1 ? 0 : (skip * take) - take;
$.ajax({
type: "POST",
url: "Default.aspx/FetchCustomers",
data: "{skip:" + skippy + ",take:" + take + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
var total = msg.d.TotalRecords;
if (total > 0) {
printCustomer(msg.d.Customers);
$("#paging").text("");
$("#paging").die("click");
// Get the page count by dividing the total records
// by the page size. This has to be rounded up
// otherwise you might not get the last page
var pageTotal = Math.ceil(total / take);
for (var i = 0; i < pageTotal; i++)
{
var newId = "anchor" + i;
var pageNo = parseInt(i + 1);
$("#paging").append("<a href=\"#pagedData\" id="
+ newId + ">" + pageNo + "</a>&nbsp;");
$("#paging a[id$=" + newId + "]").live("click",
function() {
fetchCustomer($(this).text());
});
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}

// Display the number of rows per page


function printRecordsPerPage(count) {
$("#recordsPerPage").text(count + " records per page");
}

// This function accepts a customer object


// and prints the results to the div element.
function printCustomer(msg) {
$("#result").setTemplateURL("Template.htm");
$("#result").processTemplate(msg);
}
</script>

There’s allot going on in the code above, so I’ll break it down into smaller pieces. In the
code above, the first thing that is executed is the $(document).ready event. In this event
I’m creating the slider, setting default values for the orientation, min, max, value and step
options. I have also created event handlers for the slide and change event:

$(document).ready(function() {
var $slide = $("#slider");
$slide.slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 20,
value: 10,
step: 1,
slide: function(event, ui) {
printRecordsPerPage(ui.value);
},
change: function(event, ui) {
fetchCustomer(1);
}
});
printRecordsPerPage($slide.slider("option", "value"));
fetchCustomer(1);
});

When the user runs the application, the default page size is set by the value option. When
they slide the slider to display more/less records, the slide event is triggered. This calls the
printRecordsPerPage function which updates the current value of the slider. When the user
stops sliding, the change event is triggered. That calls fetchCustomers and sets the current
page back to the beginning. fetchCustomers uses jQuery’s Ajax functionality to retrieve the
data from the server via the WebMethod. The WebMethod takes two parameters, skip and
take. The skip value is determined by what page the user is on, but the take value gets the
current value of the slider and uses that to determine the page size:

var take = $slide.slider("option", "value");


var skippy = skip == 1 ? 0 : (skip * take) - take;

This function also calls printCustomer which renders the results to the browser by using
jTemplates. jTemplates is a free plug-in that allows you to create templates that accept JSON
and output the result as standard HTML. This allows you to separate your UI from your
JavaScript code.

function printCustomer(msg) {
$("#result").setTemplateURL("Template.htm");
$("#result").processTemplate(msg);
}

<table style="border:solid 1px #000000;">


<thead>
<tr>
<th>ID</th>
<th>Company Name</th>
<th>City</th>
</tr>
</thead>
<tbody>
{#foreach $T as data}
<tr>
<td>{$T.data.CustomerID}</td>
<td>{$T.data.CompanyName}</td>
<td>{$T.data.City}</td>
</tr>
{#/for}
</tbody>
</table>

If you run the code you’ll see the records are displayed ten at a time. If you slide the slider
down, you’ll decrease the amount of records displayed per page:
And if you increase the value of the slider, you’ll display more rows per page:

I hope reading this article makes you think of different ways to interact with your users. The
entire source code of this article can be downloaded over here

Display the Text and Value of the Selected RadioButton


using jQuery

In this short article, I will demonstrate how to Display the Text and Value of the Selected
RadioButton using jQuery. This article is a sample chapter from my EBook called 51 Tips,
Tricks and Recipes with jQuery and ASP.NET Controls. The chapter content has been
modified to publish it as an article. Also please note that for demonstration purposes, I have
included jQuery code in the same page. Ideally, these resources should be created in
separate folders for maintainability.

Let us quickly jump to the solution and see how we can display the text and value of the
selected radio button:

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

<head runat="server">
<title>Retrieve the Text and Value of the selected RadioButton</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script src='../Scripts/jquery-1.3.2.min.js'
type='text/javascript'>
</script>

<script type="text/javascript">
$(function() {
var $radBtn = $("table.tbl input:radio");
$radBtn.click(function() {
var $radChecked = $(':radio:checked');
$("#para").text('')
.append("<b>Index: </b>" +
$radChecked.val() + "<br/>")
.append("<b>Value: </b>" +
$radChecked.next().text());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="smallDiv">
<h2>Select a RadioButton to display its Text and Value</h2><br />
The site I like the most : <br />
<asp:RadioButtonList ID="rbl" runat="server" class="tbl"
ToolTip="Select a Radio Button to see its text and value">
<asp:ListItem Text="dotnetcurry.com" Value="0"></asp:ListItem>
<asp:ListItem Text="devcurry.com" Value="1"></asp:ListItem>
<asp:ListItem Text="sqlservercurry.com" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<br />
<p id="para"></p>
</div>
</form>
</body>
</html>

Retrieving the index and value of a radio button is a very common requirement in our
applications and can be easily achieved using jQuery. In this example, we first retrieve the
radio buttons using

var $radBtn = $("table.tbl input:radio");

Since this is a RadioButtonList, the control gets rendered as a table. When the user clicks on
any of the radio buttons, we first store the checked radiobuttons in the $radChecked
variable to improve selector performance

var $radChecked = $(':radio:checked');

We then use:

$radChecked.val() to retrieve the value and $radChecked.next().text() to retrieve the text.

Observe how we are accessing the value of a radiobutton using:

$radChecked.next().text().
This is because the RadioButton gets rendered like this:

<td>
<input id="rbl_0" type="radio" name="rbl" value="0" />
<label for="rbl_0">dotnetcurry.com</label>
</td>

To access the value, which is inside the label, we use next() which finds the very next
sibling of each radiobutton, which in our case, is the label control. The value and text is
displayed on the page using a paragraph (para). The output looks similar to this:

See a Live Demo

This demo has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.

There are plenty of such similar recipes that I have covered in my EBook over here 51 Tips,
Tricks and Recipes with jQuery and ASP.NET Controls

I hope you liked this article and I thank you for viewing it.

If you liked the article, Subscribe to the RSS Feed or Subscribe Via Email

Testing jQuery With QUnit

One thing that’s always on my mind when I develop applications is testing. How testable is
your code? Does it rely on external processes or databases or can you easily mock these
objects? Using frameworks such as ASP.NET MVC make your code more readily testable, but
how do you test your JavaScript? Like most people I test this by hand, but the other day I
stumbled upon jQuery’s QUnit framework. Here’s what the authors say about QUnit:

“QUnit is a powerful, easy-to-use, JavaScript test suite. It's used by the jQuery project to
test its code and plugins but is capable of testing any generic JavaScript code (and even
capable of testing JavaScript code on the server-side).”

I’ll be doing three examples in this article. The first is a page with manual testing. The
second is automated testing but still relying on the UI elements. The third will be automated
testing that mocks the UI elements which mean you can test your JavaScript independently
of the page. Before we get started, this example uses the latest version of jQuery which is
1.3.2. That can be downloaded from here.

In its simplest form, QUnit contains one or more tests that contains one or more
assertions. A test is defined by adding the test function. The assertions can either by one of
the following:

 ok - A boolean assertion, equivalent to JUnit's assertTrue


 equals - A comparison assertion, equivalent to JUnit's assertEquals
 same - A deep recursive comparison assertion, working on primitive types, arrays and
objects

A simple test could look like this:

test("Sample", function() {
var addThemTogether = (1 + 1);
equals(2, addThemTogether, "Should equal two");
});

The examples in this article will involve creating a page with a text box and a span tag. If
the user types in less than seven characters, all is good, but if they type in more than 7
characters, they fail validation. Fairly easy code as I’m focusing on the testing side of
things. Okay let’s gets started.
Example 1 – Manual Testing
Open Visual Studio 2008 and create a new Web Application. Add a new web form to the
project. Add the following HTML to the page:

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


<head runat="server">
<title>Testing jQuery With QUnit</title>
<script type="text/javascript" language="javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var txt = $("input[id$=TextBox1]");
var span = $(txt).next();
$(txt).keyup(function() {
var length = $(txt).val().length;
$(span).text(length + " characters long");
$(span).css("background-color", length >= 8 ? "#FF0000" :
"#FFFFFF");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" />
<span></span>
</form>
</body>
</html>
Run the application to start testing it. If you start typing in the text box, you’ll see the
nunber of characters you have typed:

If you type more than 7 characters, you’ll be given visual feedback of the problem:

This testing is good, but we can make it better!


Example 2 – Automated Testing With UI
The same code as above but I’m adding three test functions.

<head runat="server">
<title>Testing jQuery With QUnit</title>
<script type="text/javascript" language="javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet"
href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css"
type="text/css" media="screen" />
<script type="text/javascript"
src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"
language="javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var txt = $("input[id$=TextBox1]");
var span = $(txt).next();
$(txt).keyup(function() {
var length = $(txt).val().length;
$(span).text(length + " characters long");
$(span).css("background-color", length >= 8 ? "#FF0000" :
"#FFFFFF");
});

test("Perform keyup - should fail", function() {


$(txt).val("Hello World!");
$(txt).trigger("keyup");
var color = $(span).css("background-color");
equals(color, "#ff0000", "The background color should be
#ff0000");
});

test("Perform keyup - should pass", function() {


$(txt).val("Hello!");
$(txt).trigger("keyup");
var color = $(span).css("background-color");
equals(color, "#ffffff", "The background color should be
#ffffff");
});

test("Perform keyup - should fail I think", function() {


$(txt).val("Ok");
$(txt).trigger("keyup");
var color = $(span).css("background-color");
equals(color, "#ff0000", "The background color should be
#ff0000");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" />
<span></span>
<h1 id="qunit-header">QUnit example</h1>
<ol id="qunit-tests"></ol>
</form>
</body>
</html>

In the code above I have used the same code to connect to the keyup event on the text
box. I have added three test functions. To simulate user interaction, each test copies text
into the text box and triggers the text box’s keyup event by calling the trigger function. After
each keyup event, I am calling the equals function to test the background colour of the text
box. That way I’ll know if the result is what I expect.

test("Perform keyup - should fail", function() {


$(txt).val("Hello World!");
$(txt).trigger("keyup");
var color = $(span).css("background-color");
equals(color, "#ff0000", "The background color should be #ff0000");
});

This is a nice way to automate your test. The only thing to improve is making the test
independent of the page. In the next example I’ll mock these elements so the JavaScript
can be tested independently.
Example 3 – Automated Testing With Mocking Page Elements
This example dynamically mocks the UI elements so the JavaScript can be fully tested with
the UI:

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


<head id="Head1" runat="server">
<title>Testing jQuery With QUnit</title>
<script type="text/javascript" language="javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet"
href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css"
type="text/css" media="screen" />
<script type="text/javascript"
src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"
language="javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("body").after("<input type=\"text\" id=\"TextBox1\"
/><span></span>");
var txt = $("input[id$=TextBox1]");
var span = $(txt).next();
$(txt).live("keyup", function() {
var length = $(txt).val().length;
$(span).text(length + " characters long");
$(span).css("background-color", length >= 8 ? "#FF0000" :
"#FFFFFF");
});

test("Perform keyup - should fail", function() {


$(txt).val("Hello World!");
$(txt).trigger("keyup");
var color = $(span).css("background-color");
equals(color, "#ff0000", "The background color should be
#ff0000");
});

test("Perform keyup - should pass", function() {


$(txt).val("Hello!");
$(txt).trigger("keyup");
var color = $(span).css("background-color");
equals(color, "#ffffff", "The background color should be
#ffffff");
});

test("Perform keyup - should fail I think", function() {


$(txt).val("Ok");
$(txt).trigger("keyup");
var color = $(span).css("background-color");
equals(color, "#ff0000", "The background color should be
#ff0000");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<h1 id="qunit-header">QUnit example</h1>
<ol id="qunit-tests"></ol>
</form>
</body>
</html>

To fully test this example I have removed the page elements. I’m creating the elements
dynamically using jQuery’s after function:

body").after("<input type=\"text\" id=\"TextBox1\" /><span></span>");

Because these elements are added dynamically, the only other change required is to add
the live event to the text box. This binds a handler to an event for all current and future
matched elements:

$(txt).live("keyup", function() {
var length = $(txt).val().length;
$(span).text(length + " characters long");
$(span).css("background-color", length >= 8 ? "#FF0000" : "#FFFFFF");
});

The rest of the code is the same. I can now test the JavaScript independently:

Since writing this article I am performing this type of testing for most of my critical
JavaScript code. This is a fantastic addition for anyone working with jQuery in my opinion.
The entire source code of this article can be downloaded over here
Using the jQuery the ProgressBar Widget in ASP.NET
Applications

One of the harder things to do in web development is to give the user feedback about long
running processes. This task is made simpler thanks to a widget in jQuery called the
ProgressBar. The widget takes all of the hard work out of creating the progress bar, and lets
you concentrate on updating the progress bar. This article will simulate a long running
process, and while it’s running, the progress bar will be giving the user visual feedback on
the state of the operation.

Before we get started, this example uses the latest version of jQuery which is 1.3.2. That
can be downloaded from here. You’ll also need the jQuery UI Core ProgressBar Widget and
the PorgressBar CSS files which can be downloaded from here.

Open Visual Studio 2008 and create a new Web Application. I’ve separated my project by
adding two folders, one called CSS to store the style sheets and the other called Scripts to
store the JavaScript files. To begin with add the following JavaScript and CSS file references
to the <head> HTML tag:

<link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />


<script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Scripts/ui.core.js"></script>
<script type="text/javascript" src="Scripts/ui.progressbar.js"></script>

Now that’s done let’s turn our attention to the ProgressBar widget. The ProgressBar has a
method called progressbar which accepts the parameters outlined below:
The value parameter can get or set the current value of the progress bar. I’ll begin by
setting the default value of the progress bar to zero:

$("#progressbar").progressbar({ value: 0 });

The next step is to use jQuery’s Ajax functionality to call a method in our code behind. Add
the following code:

$("#btnGetData").click(function() {
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "Default.aspx/GetText",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#progressbar").progressbar("value", 100);
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});

function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
}
}
In the above code when the user clicks the button to fetch the data, I am using the
JavaScript setInterval function to call another function every 250 milliseconds. This function
will be responsible for updating the current value of the progress bar. Next by using Ajax,
the code is calling a method called GetText, which is located in the Default.aspx.cs file. The
result of that method will be inserted into a div tag whose id is result. Add the following
GetText method:

C#

[System.Web.Services.WebMethod]
public static string GetText()
{
for (int i = 0; i < 10; i ++)
{
Thread.Sleep(1000);
}
return "All finished!";
}

VB.NET

<System.Web.Services.WebMethod> _
Public Shared Function GetText() As String
For i As Integer = 0 To 9
Thread.Sleep(1000)
Next i
Return "All finished!"
End Function

For the method to be called from jQuery, it needs to be a public static method, and needs to
be decorated with the WebMethod attribute. Inside the method, I am counting to ten by
telling the application to sleep for one second. This will simulate a long running task on the
server. The final step is to add the HTML below:

<div id="progressbar"></div>
<div id="result"></div><br />
<asp:Button ID="btnGetData" runat="server" Text="Get Data" />

If you run the application now and click the Get Data button, you’ll have a visual indication
of the long running task as the progress bar’s value is updated:

Default setting:

Once the user clicks the button the progress bar will begin the updates:
And finally when the task is finished, the progress bar will be fully loaded:

This is a nice and easy way to add more richness to your application through jQuery. The
entire source code of this article can be downloaded over here.
jQuery Tabs and Lazy Loading

Tabs are a great way to break up data if you have large amounts of data to display. The
people from jQuery have made their own tabs control. I thought it would be cool to write an
article that uses jQuery’s tab control to lazy load data from LINQ to SQL into the tabs. Well
here it is. In this article I will connect to the Northwind database using LINQ to SQL, and
display customer and product information in separate tabs. I’ll also show you one way of
lazy loading these tabs so the data is retrieved only once, not each time a tab is selected.

Update: This article, with some modifications (jTemplates), is now a part of the eBook 51
Tips, Tricks and Recipes using jQuery and ASP.NET Controls

Before we get started, this example uses the latest version of jQuery which is 1.3.2. That
can be downloaded from here. You’ll also need the jQuery UI Core Tabs Widget and the Tabs
CSS files which can be downloaded from here. You’ll also need a copy of the Northwind
database. If you don’t have a copy of the Northwind database, you can go here to download
it.

Open Visual Studio 2008 and create a new Web Application. I’ve separated my project by
adding two folders, one called CSS to store the cascading style sheets and the other called
Scripts to store the JavaScript files. To begin with add a new LINQ to SQL file to your
project and call it Northwind. Add the customer and products tables to the design surface:
Now we need to add two methods to the default page to retrieve the data from the
database. These need to be decorated with the WebMethod attribute so they can be
consumed by jQuery’s Ajax function:

C#

[WebMethod]
public static List<Customer> GetCustomers()
{
using (var dc = new NorthwindDataContext())
{
var query = from p in dc.Customers
select p;
return query.ToList();
}
}

[WebMethod]
public static List<Product> GetProducts()
{
using (var dc = new NorthwindDataContext())
{
var query = from p in dc.Products
select p;
return query.ToList();
}
}

VB.NET

<WebMethod> _
Public Shared Function GetCustomers() As List(Of Customer)
Using dc = New NorthwindDataContext()
Dim query = From p In dc.Customers _
Select p
Return query.ToList()
End Using
End Function

<WebMethod> _
Public Shared Function GetProducts() As List(Of Product)
Using dc = New NorthwindDataContext()
Dim query = From p In dc.Products _
Select p
Return query.ToList()
End Using
End Function

That’s all the server code we’ll need. Turning our attention back to the default page, open
the HTML designer and add the following JavaScript and CSS file references to the <head>
HTML tag:

<link type="text/css" href="CSS/jquery-ui-1.7.2.custom.css" rel="stylesheet"


/>
<script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui-
1.7.2.custom.min.js"></script>

First of all you need to add the following HTML. This will act as a placeholder for the data
retrieved from the database.

<div id="tabs">
<ul>
<li>
<a href="#tabs-0">Customers</a>
</li>
<li>
<a href="#tabs-1">Products</a>
</li>
</ul>
<div id="tabs-0">
<input type="hidden" id="tab0Selected" />
</div>
<div id="tabs-1">
<input type="hidden" id="tab1Selected" />
</div>
</div>

Now that’s done we can start adding the JavaScript. The following code will ensure when the
page loads, no tabs are displayed:

$('#tabs').tabs({ selected: -1 });

The tab control has a number of events, but the two events I am binding to in this article
are the select and show events. The select event is triggered when clicking a tab and the
show event is triggered when a tab is shown. The show event is critical for the lazy loading
to work. When this event is fired, I am updating a hidden field in the selected tab. Before
rushing off to the server to retrieve the data, I first check to see if the hidden control has a
value. If it does, no server code will be executed. Add the following code for the show
event:

$('#tabs').bind('tabsshow', function(event, ui) {


var tabSelected = "#tab" + ui.index + "Selected";
$(tabSelected).html("isClicked");
});

The next step is to add code to the select event. The code for this event is below:

$('#tabs').bind('tabsselect', function(event, ui) {


var callMethod;
var tabSelected = "#tab" + ui.index + "Selected";
if ($(tabSelected).text() == "") {
switch (ui.index) {
case 0:
callMethod = "Default.aspx/GetCustomers";
break;
case 1:
callMethod = "Default.aspx/GetProducts";
break;
}

$.ajax({
type: "POST",
url: callMethod,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
switch (ui.index) {
case 0:
var customers = msg.d;
for (var i = 0; i < customers.length;
i++) {
$("#tabs-
0").append(customers[i].CustomerID + ", " +
customers[i].CompanyName + ",
" +
customers[i].ContactName + ",
" +
customers[i].Address + ", " +
customers[i].City + ", " +
customers[i].Country + "<br
/>");
}
break;
case 1:
var products = msg.d;
for (var i = 0; i < products.length; i++)
{
$("#tabs-
1").append(products[i].ProductID + ", " +
products[i].ProductName + ",
" +
products[i].QuantityPerUnit +
", " +
products[i].UnitPrice + ", "
+
products[i].UnitsInStock + ",
" +
products[i].Discontinued +
"<br />");
}
break;
}
}
});
}
});

In the code above, the first step is to get the selected tab and locate the hidden field inside
the tab. If the hidden field contains text, I know the data has been loaded for this tab
previously, so don’t load it again:

var tabSelected = "#tab" + ui.index + "Selected";

if ($(tabSelected).text() == "") {

The next step is to set which server side method is to be executed. This is determined by
the tab selected:

switch (ui.index) {

case 0:
callMethod = "Default.aspx/GetCustomers";
break;
case 1:
callMethod = "Default.aspx/GetProducts";
break;
}

The next step uses jQuery’s Ajax function to execute the WebMethod. Once the method has
finished executing the success function is called. The data is passed back in the msg.d
property. The JSON returned can be viewed through Firebug if you’re using Firefox:
The final step is to render the data in the browser. Visual Studio’s Intellisense won’t be able
to find the properties returned, but you can type them in manually:

success: function(msg) {

switch (ui.index) {
case 0:
var customers = msg.d;
for (var i = 0; i < customers.length; i++) {
$("#tabs-0").append(customers[i].CustomerID + ", " +
customers[i].CompanyName + ", " +
customers[i].ContactName + ", " +
customers[i].Address + ", " +
customers[i].City + ", " +
customers[i].Country + "<br />");
}
break;
case 1:
var products = msg.d;
for (var i = 0; i < products.length; i++) {
$("#tabs-1").append(products[i].ProductID + ", " +
products[i].ProductName + ", " +
products[i].QuantityPerUnit + ", " +
products[i].UnitPrice + ", " +
products[i].UnitsInStock + ", " +
products[i].Discontinued + "<br />");
}
break;
}
}

If you run the application now you’ll be able to select a tab, and the corresponding data will
be returned from the database. You’ll also notice the code is executed once. This is a good
way to add feature rich functionality to your page without drowning it in tonnes of server
code.

The entire source code of this article can be downloaded over here

Efficient Server Side Paging With ASP.NET And jQuery

Earlier this year I did an article on Efficient Server Side Paging with the ASP.NET GridView
Control. That article is still relevant, but I thought it would be a good idea to do this using
jQuery. A big reason for using jQuery’s Ajax functionality is you eliminate the need to use
page heavy server controls such as the GridView, and you don’t bloat your page with tonnes
of ViewState. Well here’s one way to replicate custom paging in the GridView using jQuery.
Before we get started, this example uses the latest version of jQuery which is 1.3.2. That
can be downloaded from here. You’ll also need a copy of the Northwind database. If you
don’t have a copy of the Northwind database, you can go here to download it.

Open Visual Studio 2008 and create a new Web Application. To begin with add a new LINQ
to SQL Classes file to your project and call it Northwind. Add the customer table to the
design surface:

Save and build your project. Now that is done I’m going to create a custom class to return
to the client. I’m creating it this way because the method needs to return not only a list of
customers, but it also needs to return the total customer count for the paging to function
correctly. Add a new class to your web application and call it CustomerData. Add the
following code:

C#

public class CustomerData


{
public List<Customer> Customers { get; set; }
public int TotalRecords { get; set; }
}

VB.NET

Public Class CustomerData


Private privateCustomers As List(Of Customer)
Public Property Customers() As List(Of Customer)
Get
Return privateCustomers
End Get
Set(ByVal value As List(Of Customer))
privateCustomers = value
End Set
End Property
Private privateTotalRecords As Integer
Public Property TotalRecords() As Integer
Get
Return privateTotalRecords
End Get
Set(ByVal value As Integer)
privateTotalRecords = value
End Set
End Property
End Class

The CustomerData class has two properties. The Customers property will contain the list of
customers, and TotalRecords will hold the total number of records. Now we need to add one
method to the default page to retrieve the data. This needs to be decorated with the
WebMethod attribute, so it can be consumed by jQuery’s Ajax function. Add the following
method to fetch the customer data.

C#

[WebMethod]
public static CustomerData FetchCustomers(int skip, int take)
{
var data = new CustomerData();
using (var dc = new NorthwindDataContext())
{
var query = (from p in dc.Customers
select p)
.Skip(skip)
.Take(take)
.ToList();
data.Customers = query;
data.TotalRecords = (from p in dc.Customers
select p).Count();
}
return data;
}

VB.NET

<WebMethod> _
Public Shared Function FetchCustomers(ByVal skip As Integer, ByVal take As
Integer) As CustomerData
Dim data = New CustomerData()
Using dc = New NorthwindDataContext()
Dim query = ( _
From p In dc.Customers _
Select p).Skip(skip).Take(take).ToList()
data.Customers = query
data.TotalRecords = ( _
From p In dc.Customers _
Select p).Count()
End Using
Return data
End Function

In the code above, the method acceps two parameters, skip and take, which are integer
values that will be used to run the IQueryable Take and Skip methods. These methods create
an SQL statement that only returns records between the rows starting at the Take value,
and then skipping all the rows in the Skip value instead of the whole table. That’s the server
code done! Now to turn our attention to the HTML! To begin with add the following
JavaScript and CSS file references to the <head> HTML tag:

<script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script>

Next you need to add the following HTML. This will act as a placeholder for the data
retrieved from the database.

<input id="btnSearch" type="button" value="Search" />


<span id="totalRecords"></span>
<div id="result"></div>
<div id="paging"></div>

Now that’s done we can start adding the JavaScript. The following is the complete code, but
I’ll break it down into smaller pieces:

var pageSize = 10;


function pageData(e) {
var skip = e == 1 ? 0 : (e * pageSize) - pageSize;
$.ajax({
type: "POST",
url: "Default.aspx/FetchCustomers",
data: "{skip:" + skip + ",take:" + pageSize + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
printCustomer(msg);
}
});
return false;
}

$(document).ready(function() {
$("#btnSearch").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/FetchCustomers",
data: "{skip:0,take:" + pageSize + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
var total = msg.d.TotalRecords;
if (total > 0) {
printCustomer(msg);
$("#paging").text("");
// Get the page count by dividing the total records
// by the page size. This has to be rounded up
// otherwise you might not get the last page
var pageTotal = Math.ceil(total / pageSize);
for (var i = 0; i < pageTotal; i++) {
$("#paging").append("<a href=\"#\" onClick=\"pageData(" + (i + 1) + ")\">" +
(i + 1) + "</a>&nbsp;");
}
}
else {
$("#paging").text("No records were found.");
}
$("#totalRecords").text("Total records: " + total);
}
});
});
});

// This function accepts a customer object


// and prints the results to the div element.
function printCustomer(msg) {
$("#result").text("");
var customers = msg.d.Customers;
for (var i = 0; i < customers.length; i++) {
$("#result").append(customers[i].CustomerID + ", ");
$("#result").append(customers[i].CompanyName + ", ");
$("#result").append(customers[i].ContactName + ", ");
$("#result").append(customers[i].ContactTitle + ", ");
$("#result").append(customers[i].Address + ", ");
$("#result").append(customers[i].City + ", ");
$("#result").append(customers[i].Region + "<br />");
}
}

In the code above, the first thing I have done is create a variable to hold the total number
of records to display per page:

var pageSize = 10;

The user will run the search by clicking the HTML button btnSearch. I am using jQuery to
attach code to the buttons click event. Once the data is retrieved from the server, the
customers will be returned in the msg.d.Customers property, and the total count will be in
the msg.d.TotalRecords property. To enable paging, the TotalRecords will be dived by the
pageSize value to calculate how many paging options will need to be displayed.

$(document).ready(function() {
$("#btnSearch").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/FetchCustomers",
data: "{skip:0,take:" + pageSize + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
var total = msg.d.TotalRecords;
if (total > 0) {
printCustomer(msg);
$("#paging").text("");
// Get the page count by dividing the total records
// by the page size. This has to be rounded up
// otherwise you might not get the last page
var pageTotal = Math.ceil(total / pageSize);
for (var i = 0; i < pageTotal; i++) {
$("#paging").append("<a href=\"#\"
onClick=\"pageData(" + (i + 1) + ")\">" + (i + 1) +
"</a>&nbsp;");
}
}
else {
$("#paging").text("No records were found.");
}
$("#totalRecords").text("Total records: " + total);
}
});
});
});

Each time the user clicks on a paging option, they’ll run a JavaScript function called
pageData. This function will use jQuery’s Ajax functionality to call the server side code, but
it will calculate the records to skip and take by the users selection:

function pageData(e) {
var skip = e == 1 ? 0 : (e * pageSize) - pageSize;
$.ajax({
type: "POST",
url: "Default.aspx/FetchCustomers",
data: "{skip:" + skip + ",take:" + pageSize + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
printCustomer(msg);
}
});
return false;
}

Finally to reduce duplicate code, I have created a function called printCustomers. This will
be responsible for enumerating through each customer record and rendering it in the
browser:

// This function accepts a customer object


// and prints the results to the div element.
function printCustomer(msg) {
$("#result").text("");
var customers = msg.d.Customers;
for (var i = 0; i < customers.length; i++) {
$("#result").append(customers[i].CustomerID + ", ");
$("#result").append(customers[i].CompanyName + ", ");
$("#result").append(customers[i].ContactName + ", ");
$("#result").append(customers[i].ContactTitle + ", ");
$("#result").append(customers[i].Address + ", ");
$("#result").append(customers[i].City + ", ");
$("#result").append(customers[i].Region + "<br />");
}
}
If you run the code you’ll see the records are displayed ten at a time. To view the real
efficiency you can use SQL Profiler to see the SQL that is executed on the database. The
following code is a sample of what is executed on the SQL Server:

SELECT [t1].[CustomerID], [t1].[CompanyName], [t1].[ContactName],


[t1].[ContactTitle], [t1].[Address], [t1].[City], [t1].[Region],
[t1].[PostalCode], [t1].[Country], [t1].[Phone], [t1].[Fax]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t0].[CustomerID], [t0].[CompanyName],
[t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City],
[t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax])
AS [ROW_NUMBER], [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
[t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region],
[t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]

The code that is generated, utilises the ROW_NUMBER() function which limits the numbers
of rows that are returned.

By handling the paging as shown in this example, your ASP.NET website will be able to
display thousands of records efficiently using jQuery and your page weight will be reduced
because you’re not using server side controls and your ViewState will be reduced because of
this too. This will not only improve performance on the web server, but it will also decrease
the amount of data that is sent to the client.

The entire source code of this article can be downloaded over here

If you liked the article, Subscribe to the RSS Feed or Subscribe Via Email

Malcolm Sheridan is an independent contractor who has been working with Microsoft
technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly
enjoys ASP.NET.

Using jQuery To Create Stunning Tooltips in your


ASP.NET Applications

I’ve mentioned recently there are tonnes of jQuery plugins on the internet. Well the other
day I ran into one that was totally awesome! It’s a plugin called jQuery Tools and can be
downloaded from here. The makers of this tool describe it this way:

“jQuery Tools is a collection of the most important user interface components for the web.
These are tabs and accordions, tooltips, overlays, exposing effects and scrollables. They can
dramatically improve the usability and responsiveness of your site. They mainly focus on
presenting information and visual appeal. After all, this is exactly what most websites
desperately want: to present their content to the reader in an easy and visually pleasing
manner.”
I’ll be focusing some future articles on these tools, but this article will concentrate on how to
create stunning tooltips using this plugin. The end result in this article will show you how to
create these tooltips using dynamic data by using jQuery’s Ajax functionality. The end result
will look something like this:

Before we get started, this example uses the latest version of jQuery which is 1.3.2. That
can be downloaded from here. The jQuery Tools and can be downloaded from here.

The jQuery Tools plugin has quite a few options when it comes time to configuration, but
the one you should not forget is the tip attribute. This jQuery selector selects the tooltip
element being used. The attribute that will allow you to position the tooltip is funnily enough
called position. The position property specifies the position in relation to the trigger element.
For example, a value of 'bottom center' will place the tooltip on the bottom edge of the
trigger, centred horizontally. Other values are:

 top center, top right, center right, bottom right, bottom left, center left and top left

To make this real, instead of showing this tooltip against static data such as images, I’m
going to use jQuery’s Ajax functionality to query the server for a list of running
processes. Okay let’s gets started. Open Visual Studio 2008 and create a new Web
Application. First off add a new class to the project and call it ProcessInfo. This class will
hold information about the process. Add the following code to the class:
C#

public class ProcessInfo


{
public string ProcessName { get; set; }
public string MainWindowTitle { get; set; }
public long PagedMemorySize64 { get; set; }
}

VB.NET

Public Class ProcessInfo


Private privateProcessName As String
Public Property ProcessName() As String
Get
Return privateProcessName
End Get
Set(ByVal value As String)
privateProcessName = value
End Set
End Property
Private privateMainWindowTitle As String
Public Property MainWindowTitle() As String
Get
Return privateMainWindowTitle
End Get
Set(ByVal value As String)
privateMainWindowTitle = value
End Set
End Property
Private privatePagedMemorySize64 As Long
Public Property PagedMemorySize64() As Long
Get
Return privatePagedMemorySize64
End Get
Set(ByVal value As Long)
privatePagedMemorySize64 = value
End Set
End Property
End Class

The next step is to open the Default.aspx.cs file and add the following code:

C#

[WebMethod]
public static List<ProcessInfo> GetRunningProcesses()
{
var query = (from p in System.Diagnostics.Process.GetProcesses()
select new ProcessInfo
{
ProcessName = p.ProcessName,
MainWindowTitle = p.MainWindowTitle,
PagedMemorySize64 =
p.PagedMemorySize64
}).ToList();
return query;
}

VB.NET

<WebMethod> _
Public Shared Function GetRunningProcesses() As List(Of ProcessInfo)
Dim query = ( _
From p In System.Diagnostics.Process.GetProcesses() _
Select New ProcessInfo With {.ProcessName = p.ProcessName,
.MainWindowTitle = p.MainWindowTitle, .PagedMemorySize64 =
p.PagedMemorySize64}).ToList()
Return query
End Function

The code above will be called by jQuery’s Ajax function. It returns a list of running process
on the machine thanks to the Process object. The Process class provides access to local and
remote processes. The LINQ query will return a generic list of ProcessInfo objects that will
be used to create the tooltips. The next step is to add the JavaScript. Open the Default.aspx
page and add the following jQuery code to the <head> section of the page. Ideally
JavaScript should go to a separate .js file, however for this example; I’ll keep it in the same
page:
<script language="javascript" type="text/javascript" src="Scripts/jquery-
1.3.2.js"></script>
<script language="javascript" type="text/javascript"
src="http://cdn.jquerytools.org/1.1.1/jquery.tools.min.js"></script>
<script language="javascript" type="text/javascript">
function showToolTip() {
$("#results span[title]").tooltip({
position: "center right",
opacity: 0.7,
tip: "#demotip",
effect: "fade"
});
}

$(document).ready(function() {
$("#btnSearch").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetRunningProcesses",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
var processInfo = msg.d;
$("#results").text("");
for (var i = 0; i < processInfo.length; i++) {
// create the title for each item
var title = "Process&nbsp;Name:&nbsp;" +
processInfo[i].ProcessName +
"&lt;BR&gt;" +
"Paged&nbsp;Memory&nbsp;Size64:&nbsp;
" +
processInfo[i].PagedMemorySize64;

$("#results").append("<span
onmouseover=\"showToolTip()\" title=" + title + ">" +
processInfo[i].ProcessName +
"</span><div id=\"spacer\"></div><br />");
}
}
});
});
});
</script>

In the code above I am binding to the input button’s click event. When the user clicks the
button, it will execute the WebMethod GetRunningProcesses. A generic list containing the
ProcessInfo data will be returned in the msg.d argument. For each process returned, a span
tag will be appended in the div element. When the user hover’s their mouse over the tag,
the JavaScript function showToolTip will run. This function is responsible for displaying the
tooltip:

function showToolTip() {
$("#results span[title]").tooltip({
position: "center right",
opacity: 0.7,
tip: "#demotip",
effect: "fade"
});
}

Using jQuery’s selectors the tooltip will find the related span tag to trigger the tooltip. The
tool looks for the element that is placed next to the tooltip to be the tooltip. The return
value is a jQuery object associated with the selection. The result is a stunning tooltip as
the screen shot below shows:

The information in the tooltip can be configured as it’s just HTML. So if you want you can
display a nice image to the user so they’ll be able to associate the process by the icon. The
background image of the tooltip is configurable too. The styling for the tooltip is below:

#demotip {
display:none;
background:transparent
url(http://flowplayer.org/tools/img/tooltip/black_arrow.png);
font-size:12px;
height:70px;
width:160px;
padding:25px;
color:#fff;
}

This is a nice addition to your jQuery ensemble. The entire source code of this article can
be downloaded over here

5 Different Ways of Showing and Hiding Content of an


ASP.NET Panel using jQuery

In this short and simple article, we will explore 5 different ways of expanding and collapsing
an ASP.NET Panel using jQuery. Sometime back, I had covered a similar article where I
demonstrated how to create a Smooth Cascading Effect with ASP.NET Panels using jQuery.

In this article, I will be making use of the jQuery Effects API to demonstrate some cool
effects on the ASP.NET Panel.
Note: I assume you are familiar with jQuery. If you are new to jQuery, then before moving
ahead, I would recommend you to check out Using jQuery with ASP.NET - A Beginner's
Guide. Please do take a note that this example uses the latest version of jQuery 1.3.2 and
jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.

Step 1: Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’
from the templates > Choose your language (C# or VB) > Enter the location > Ok.

Step 2: In the <head> section, add a reference to the jQuery library as shown below

<head runat="server">
<title>Show Hide ASP.NET Panels in Different Ways</title>
<script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</script>

You can also download the jQuery file and reference it.

Step 3: The next step is to create an interface for showing the different effects on the
ASP.NET Panel. Add an ASP.NET Panel control and a few ASP.NET Hyperlink controls to the
page. I have also added some text to the Panel control as shown below:

<body>
<form id="form1" runat="server">
<asp:HyperLink ID="Link1" runat="server" NavigateUrl="#">Using slideToggle
</asp:HyperLink><br />
<asp:HyperLink ID="Link2" runat="server" NavigateUrl="#">Using Toggle
</asp:HyperLink><br />
<asp:HyperLink ID="Link3" runat="server" NavigateUrl="#">Using Animate
</asp:HyperLink><br />
<asp:HyperLink ID="Link4" runat="server" NavigateUrl="#">Using slideUp and
slideDown
</asp:HyperLink><br />
<asp:HyperLink ID="Link5" runat="server" NavigateUrl="#">Display Text
</asp:HyperLink>

<asp:Panel ID="panelText" runat="server" CssClass="panel">


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc
turpis nunc, placerat ac, bibendum non, pellentesque nec, odio.
Nulla fringilla aliquet nibh. Donec placerat, massa id commodo
ornare, justo lectus faucibus leo, in aliquam nisl quam varius
velit. Maecenas ullamcorper. Aliquam lectus metus, scelerisque
ac, scelerisque vitae, sodales eu, metus. Sed varius nisi sit
amet turpis. Mauris a arcu iaculis risus sodales dignissim.
Aliquam ac risus. Donec turpis. Sed sit amet mi. Nam sem nunc,
suscipit quis, cursus non, facilisis nec, diam. Donec nec mi
semper urna interdum ultrices. Sed tellus. Sed sodales, quam
sit amet dignissim ornare, orci velit blandit augue, ut pretium
diam pede eget felis. Maecenas turpis justo, dapibus non,
scelerisque et, consequat id, est. Mauris ornare. Donec
posuere ligula et nulla. Quisque sollicitudin libero vitae
dolor.Curabitur elementum venenatis lectus. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Cum sociis natoque penatibus et magnis dis parturient
montes, nascetur ridiculus mus. Nam velit. Quisque eros nisi,
congue id, aliquam ac, interdum in, velit. Duis cursus tellus
molestie libero. Cras scelerisque pellentesque nisl. Phasellus
adipiscing pretium mi. Curabitur faucibus nisl sit amet ante.
Pellentesque lacinia erat a nisi molestie lacinia. In erat
metus, tincidunt id, consequat nec, blandit bibendum, quam.
Nunc a tortor.
</asp:Panel>
</form>
</body>

The Panel has a CssClass set to ‘panel’ which looks similar to the following:

<style type="text/css">
.panel{
display:none;
}
</style>

Let us now demonstrate some ways to show and hide the content of the ASP.NET Panel with
some jQuery effects.

Note: If you are using MasterPage, check my post over here Access an ASP.NET control on a
MasterPage using jQuery

Method 1: Using slideToggle to toggle the visibility of the Panel by adjusting its height.

<script type="text/javascript">
$(function() {
$("#Link1").click(function(evt) {
evt.preventDefault();
$('#panelText').slideToggle('slow');
});
});
</script>

Method 2: Using Toggle to display and hide the Panel with a nice animation effect

<script type="text/javascript">
$(function() {
$("#Link2").click(function(evt) {
evt.preventDefault();
$('#panelText').toggle('fast');
});
});
</script>

Method 3: Using Animate to run custom animations on the properties of the Panel. Here we
are animating the height, margin and opacity.

<script type="text/javascript">
$(function() {
$("#Link3").click(function(evt) {
evt.preventDefault();
$("#panelText").animate({
height: 'toggle', margin: 'toggle', opacity: 'toggle'
}, 500);
});
});
</script>

Method 4: Using slideUp and slideDown for hiding and showing the Panel by adjusting the
Height property. Here we first check to see if the Panel is hidden. If it is, then slideDown,
else slideUp.

<script type="text/javascript">
$(function() {
$("#Link4").click(function(evt) {
evt.preventDefault();
if ($('#panelText').is(":hidden")) {
$("#panelText").slideDown("fast");
} else {
$("#panelText").slideUp("fast");
}
});
});
</script>

Method 5: Using Toggle again, but this time changing the Text of the Link that indicates
the action to the user. To start with, the user sees ‘Display Text’. On clicking the link, the
link text changes to ‘Hide Text’.

<script type="text/javascript">
$(function() {
$('#Link5').click(function(ev) {
ev.preventDefault();
$('#panelText').toggle('slow');
$('#Link5')
.text(($('#Link5').text() == 'Display Text'
? 'Hide Text' : 'Display Text'))

});
</script>

Shown above were 5 different ways of showing/hiding the contents of an ASP.NET Panel.
The samples were tested on IE 7, Firefox 3 and Chrome 2. There are some other ways too,
like using hide() and show() with animation, to hide contents of an ASP.NET Panel, but I
leave that to you to implement and find out other ways. That’s the best way to learn a
technology. Try!

You can view a Live Demo of the techniques demonstrated over here. The entire source
code of this article can be downloaded over here.

I hope you liked the article and I thank you for viewing it.

GridView Selection and Postback using jQuery

Recently Suprotim Agarwal wrote a cool article on GridView UI Tips and Tricks using
jQuery. In one of his examples, he demonstrated how to highlight a row in a GridView. I
thought I would take Suprotim’s example one step further and demonstrate how to perform
a postback once you have selected the row.

Before we get started, if you’re not familiar with jQuery, Suprotim has also written an article
on beginning jQuery called Using jQuery with ASP.NET - A Beginner's Guide. This example uses the
latest version of jQuery which is 1.3.2 and can be downloaded here.

Okay Lets get started! Open Visual Studio 2008 and create a new Web Application. This
example won’t hook into a database, but we will create a class to mock a table and retrieve
data from it instead. Right click on the project and choose Add > Class. Name the class
Employee. Open the Employee class and add the following code:

C#

public class Employee


{
public int ID { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public string Department { get; set; }
}

VB.NET

Public Class Employee

Private privateID As Integer


Public Property ID() As Integer
Get
Return privateID
End Get
Set(ByVal value As Integer)
privateID = value
End Set
End Property
Private privateGivenName As String
Public Property GivenName() As String
Get
Return privateGivenName
End Get
Set(ByVal value As String)
privateGivenName = value
End Set
End Property
Private privateSurname As String
Public Property Surname() As String
Get
Return privateSurname
End Get
Set(ByVal value As String)
privateSurname = value
End Set
End Property
Private privateDepartment As String
Public Property Department() As String
Get
Return privateDepartment
End Get
Set(ByVal value As String)
privateDepartment = value
End Set
End Property
End Class

The Employee class contains four properties. The ID property is going to the unique
identifier, so this is what we’ll use to get the selection from the user.

Open the Default.aspx page and the following code:

<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">


<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image runat="server"
ID="imgPeople" ImageUrl="~/People_031.gif"
/>
<asp:Label CssClass="hideId" runat="server"
ID="lblID" Text='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GivenName" />
<asp:BoundField DataField="Surname" />
<asp:BoundField DataField="Department" />
</Columns>
</asp:GridView>

The GridView has AutoGenerateColumns set to false. This is because we don’t want to
display the ID field. I have created an ItemTemplate for this and am hiding it from the user
by using a CSS class called hideId. This sets the display style to none. Instead of showing
an empty table cell, an image will be displayed instead.

The next step is to create a collection of Employee objects and bind that to the GridView
control. Open the Default.aspx.cs page and add the following code:

C#

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
var names = new List<Employee>();
names.Add(new Employee() { ID = 1, Surname =
"sheridan", GivenName = "malcolm", Department = "sales" });
names.Add(new Employee() { ID = 2, Surname =
"sheridan", GivenName = "debby", Department = "it" });
names.Add(new Employee() { ID = 3, Surname =
"sheridan", GivenName = "livvy", Department = "real estate" });
grdEmployee.DataSource = names;
grdEmployee.DataBind();
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


If (Not IsPostBack) Then
Dim names = New List(Of Employee)()
names.Add(New Employee() With {.ID = 1, .Surname =
"sheridan", .GivenName = "malcolm", .Department = "sales"})
names.Add(New Employee() With {.ID = 2, .Surname =
"sheridan", .GivenName = "debby", .Department = "it"})
names.Add(New Employee() With {.ID = 3, .Surname =
"sheridan", .GivenName = "livvy", .Department = "real estate"})
grdEmployee.DataSource = names
grdEmployee.DataBind()
End If
End Sub

Now we have data in the GridView, let’s add some JavaScript to highlight the row when the
user moves their mouse and make the GridView execute a postback. Add the following
code to the head of the Default.aspx page:

<script language="javascript" type="text/javascript" src="jquery-


1.3.2.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("tr").filter(function() {
return $('td', this).length && !$('table', this).length
})
.click(function() {
__doPostBack('grdEmployee', $(this).find("span").text());
})
.mouseover(function() {
$(this).css("cursor", "hand");
})
.css({ background: "ffffff" }).hover(
function() { $(this).css({ background: "#C1DAD7" }); },
function() { $(this).css({ background: "#ffffff" }); }
);
});
</script>

The click event is handled by the .click method. This method takes a function as a
parameter and runs the __doPostBack function which is an ASP.NET JavaScript function that
is automatically rendered when you want to perform a postback. This is normally generated
by controls that have AutoPostBack set to true. Because the GridView does not have an
AutoPostBack property, the page will not render the __doPostBack function. To get this
JavaScript rendered, you need to add the following into the page load event:

ClientScript.GetPostBackEventReference(new
System.Web.UI.PostBackOptions(this));

This tells ASP.NET to render __doPostBack:


function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
__doPostBack will submit the form and accepts two parameters:

1. eventTarget – the control submitting the data

2. eventArgument – additional information

The JavaScript in this example executes when a user clicks the TR. It will raise the click event
and run

__doPostBack and pass in the ID of the selected row. Remember the ID column is an
ItemTemplate that

has a Label control hidden by CSS. ASP.NET Labels are rendered as span tags. The
JavaScript will find the

text of the span tag and pass that into the function as the eventArgument.

In the page load event, we need to add some code that looks for our postback by looking into
the
Request.Form collection. Add the following code to the page load event:

C#

if (!string.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
if (Request.Form["__EVENTTARGET"] == "javaScriptEvent")
{
ProcessGridSelection(Request.Form["__EVENTARGUMENT"]);
}
}

VB.NET

If (Not String.IsNullOrEmpty(Request.Form("__EVENTTARGET"))) Then


If Request.Form("__EVENTTARGET") = "javaScriptEvent" Then
ProcessGridSelection(Request.Form("__EVENTARGUMENT"))
End If
End If
Now when the user clicks a row in the GridView, the ID of the row will be passed through
as the __EVENTARGUMENT value. From there I have created a separate function called
ProcessGridSelection which adds the ID to a session variable and redirects the user to a
separate page and displays the selected ID:

C#

private void ProcessGridSelection(string p)


{
Session["Selection"] = p;
Response.Redirect("~/SelectedRow.aspx");
}

VB.NET

Private Sub ProcessGridSelection(ByVal p As String)


Session("Selection") = p
Response.Redirect("~/SelectedRow.aspx")
End Sub

To finish this, add a new web form and name it SelectedRow.aspx. Add a Label to the page
and add the following code in the page load event:

C#

protected void Page_Load(object sender, EventArgs e)


{
if (Session["Selection"] != null)
{
lblSelectedRow.Text = "Selected ID is " +
Session["Selection"] as string;
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


If Session("Selection") IsNot Nothing Then
lblSelectedRow.Text = "Selected ID is " &
TryCast(Session("Selection"), String)
End If
End Sub

We’re done! We have got a control that highlights where the user is in a GridView and
allows them to click anywhere to post data. Allowing the user to make a selection from
anywhere in the GridView makes your application more slick and professional in my
opinion. The entire source code of this article can be downloaded from here

Consume an ASP.NET WebService returning List<> with


Dates using jQuery
In this article, we will see how to consume an ASP.NET WebService using jQuery. I will be
demonstrating how to consume a .NET List<> returning Date fields via a .NET webservice,
using jQuery. We will be using both the jQuery.ajax ($.ajax) and the jMSAjax plug-in to
retrieve data from an ASP.NET WebService. JSON does not handle dates well and we will
see how the jMSAjax plug-in supports ASP.NET Date formatting.

Note: I assume you are familiar with jQuery. If you are new to jQuery, then before moving
ahead, I would recommend you to check out Using jQuery with ASP.NET - A Beginner's
Guide. Please do take a note that this article uses jQuery’s current version - jQuery 1.3.2
and jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.

Let’s create our webservice first.

Step 1: Open Visual Studio 2008 > File > New > WebSite > Give it a name and location
and click OK.

Step 2: Now right click the project in the Solution Explorer > Add New Item > Select
WebService from the templates > Give it a name ‘EmployeeList.asmx’ and click on Add.

Step 3: A code file gets created in the App_Code directory. The default code for the
WebService contains a ‘Hello World’ method. Remove the method and replace it with our
own method that will retrieve Employee details from the Northwind database. The code will
look similar to the following:

C#

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
using System.Data;

///<summary>
/// Summary description for EmployeeList
///</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class EmployeeList : System.Web.Services.WebService {

public EmployeeList () {

//Uncomment the following line if using designed components


//InitializeComponent();
}

[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]


[WebMethod]
public List<Employee> GetEmployees()
{
string nwConn =
System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnect
ionString"].ConnectionString;
var empList = new List<Employee>();
using (SqlConnection conn = new SqlConnection(nwConn))
{
const string sql = @"SELECT TOP 10 FirstName, LastName, Title,
BirthDate FROM Employees";
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader dr = cmd.ExecuteReader(
CommandBehavior.CloseConnection);
if (dr != null)
while (dr.Read())
{
var emp = new Employee
{
FirstName = dr.GetString(0),
LastName = dr.GetString(1),
Title = dr.GetString(2),
BirthDate = dr.GetDateTime(3)
};
empList.Add(emp);
}
return empList;
}
}
}

public class Employee


{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public DateTime BirthDate { get; set; }
}

VB.NET

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Data.SqlClient
Imports System.Data

' To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class EmployeeList
Inherits System.Web.Services.WebService

<ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json),
WebMethod()> _
Public Function GetEmployees() As List(Of Employee)
Dim nwConn As String =
System.Configuration.ConfigurationManager.ConnectionStrings("NorthwindConnect
ionString").ConnectionString
Dim empList = New List(Of Employee)()
Using conn As New SqlConnection(nwConn)
Const sql As String = "SELECT TOP 10 FirstName, LastName, Title,
BirthDate FROM Employees"
conn.Open()
Using cmd As New SqlCommand(sql, conn)
Dim dr As SqlDataReader =
cmd.ExecuteReader(CommandBehavior.CloseConnection)
If dr IsNot Nothing Then
Do While dr.Read()
Dim emp = New Employee With {.FirstName =
dr.GetString(0), .LastName = dr.GetString(1), .Title = dr.GetString(2),
.BirthDate = dr.GetDateTime(3)}
empList.Add(emp)
Loop
End If
Return empList
End Using
End Using
End Function

End Class

Public Class Employee


Private privateFirstName As String
Public Property FirstName() As String
Get
Return privateFirstName
End Get
Set(ByVal value As String)
privateFirstName = value
End Set
End Property
Private privateLastName As String
Public Property LastName() As String
Get
Return privateLastName
End Get
Set(ByVal value As String)
privateLastName = value
End Set
End Property
Private privateTitle As String
Public Property Title() As String
Get
Return privateTitle
End Get
Set(ByVal value As String)
privateTitle = value
End Set
End Property
Private privateBirthDate As DateTime
Public Property BirthDate() As DateTime
Get
Return privateBirthDate
End Get
Set(ByVal value As DateTime)
privateBirthDate = value
End Set
End Property
End Class

As you can observe in the code above, we are instantiating a List<Employee> and then
using the DataReader to populate the list. We then return this list to the calling function. A
very important point to observe is that our method is decorated with the
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] which
enables the response to be serialized as a JSON string, also making it AJAX friendly.
Personally, I think this attribute is way cool since it enables my runtime to deliver JSON
objects, without me getting into any JSON transformation nitty-gritty’s.

The web.config file will have an entry for the connectionstring similar to the following:

<connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data
Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
</connectionStrings>

With our webservice ready, our first approach will involve retrieving data using the $.ajax
method and observe the shortcomings of JSON objects while expressing fields like Date.

Step 4: Go to your Default.aspx and add the following jQuery code to retrieve data from
the ASP.NET WebService using $.ajax method

<head runat="server">
<title>Access ASP.NET WebService using jQuery</title>

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "EmployeeList.asmx/GetEmployees",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(list) {
$("#Something").append("<ul id='bullets'></ul>");
for (i = 0; i < list.d.length; i++) {
$("#bullets").append("<li>" + list.d[i].FirstName
+ " : " + list.d[i].LastName + " : " +
list.d[i].BirthDate + "</li>");
}
},
error: function(e) {
$("#Something").html("There was an error retrieving
records");
}
});

});
</script>

</head>
<body>
<form id="form1" runat="server">
<div id="Something">

</div>
</form>
</body>
</html>

On running your application, you will get an output similar to the following:

As you can observe in the screenshot, the dates are not being handled well in JSON. The
DateTime is serialized as an escaped JavaScript Date initializer - /Date(-124003800000)/.
Dave Ward has explained this behavior quite well on his blog. You can also find some
information on this behavior at schotime’s blog, the creator of the jMSAjax plug-in.

Note: To call a remote webservice, check this technique described by Jason

Resolving the JSON Date formatting

Enter the jMSAjax plug-in! The jMSAjax plug-in adds additional capabilities to the existing
$.ajax to support ASP.NET Date formatting and resolve other shortcomings. It also does not
require you to access the ‘d’ property (like we did while using $.ajax) to access data.
Additional advantages are listed here.

To use this plug-in, first download the jMSAjax plug-in over here. Then add a reference to
this file in the <head> section of your page. Here’s how to use the jMSAjax plug-in to
access a JSON Serialized List<> returning Date objects.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Access ASP.NET WebService using jQuery</title>

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>


<script src="Scripts/jquery.jmsajax.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {

$.jmsajax({
url: "EmployeeList.asmx",
method: "GetEmployees",
dataType: "msjson",
success: function(list) {
$("#Something").append("<br/><ul id='bullets'></ul>");
for (i = 0; i < list.length; i++) {
$("#bullets").append("<li>" + list[i].FirstName
+ " : " + list[i].LastName + " : " +
list[i].BirthDate + "</li>");
}
},
error: function(e) {
$("#Something").html("There was an error retreiving
records");
}
});
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div id="Something">

</div>
</form>
</body>
</html>

The output of the application is shown below.


As you can observe, the dates returned by JSON are well formatted now! Way cool and a
great plug-in by Schotime!

I hope this article was useful and I thank you for viewing it. The entire source code of this
article can be downloaded from here

Upload Multiple Files in ASP.NET using jQuery

Continuing my ‘no less than an exciting’ journey of exploring ASP.NET with jQuery, today’s
article will demonstrate how to Upload multiple files in ASP.NET using jQuery.
Fyneworks.com has created a ‘jQuery Multiple File Upload Plugin’. You can download this
plug-in here http://www.fyneworks.com/jquery/multiple-file-upload/

As described by the creator of this plug-in, The Multiple File Upload Plugin (jQuery.MultiFile)
is a non-obstrusive plugin for the jQuery Javascript library that helps users easily select
multiple files for upload quickly and easily whilst also providing some basic validation
functionality to help developers idenfity simple errors, without having to submit the form
(ie.: upload files).

In this article, I will demonstrate how to use this plug-in with ASP.NET to upload multiple
files. We will also display information about the files uploaded – like the name, size and type
of the file.

I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead,
I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide.
Please do take a note that this article uses jQuery’s current version - jQuery 1.3.2 and
jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.

Step 1: Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’
from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the
Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.

Step 2: Download jQuery 1.3.2 , jQuery VS 2008 Doc and the Multiple File Upload PlugIn.
Create a ‘Scripts’ folder in the Solution Explorer of your project and add these files to this
folder.
Assuming you have downloaded these files, create a reference to these files in the <head>
section of your page as shown below:

<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js"
type="text/javascript"></script>
<script src="Scripts/jquery.MultiFile.js"
type="text/javascript"></script>
</head>

Step 3: Now drag and drop an ASP.NET ‘FileUpload’ control from the toolbox to the page.
Also add a Button control to the page. This Button control will trigger the upload to the
server.

<div>
<asp:FileUpload ID="FileUpload1" runat="server" class="multi" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload All"
onclick="btnUpload_Click" />
</div>

Observe that the FileUpload has class=”multi” set on it. This attribute is mandatory.

Step 4: The last step is to add code to upload button. Add the following code:

C#

protected void btnUpload_Click(object sender, EventArgs e)


{
try
{
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
System.IO.Path.GetFileName(hpf.FileName));
Response.Write("<b>File: </b>" + hpf.FileName +
" <b>Size:</b> " +
hpf.ContentLength + " <b>Type:</b> " +
hpf.ContentType + " Uploaded Successfully <br/>");
}
}
}
catch (Exception ex)
{

}
}

VB.NET
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnUpload.Click
Try
' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("MyFiles") & "\" &
System.IO.Path.GetFileName(hpf.FileName))
Response.Write("<b>File: </b>" & hpf.FileName &
" <b>Size:</b> " & hpf.ContentLength & " <b>Type:</b> " & hpf.ContentType & "
Uploaded Successfully <br/>")
End If
Next i
Catch ex As Exception

End Try
End Sub

As shown in the code sample above, the ‘HttpFileCollection’ class is used to retrieve all the
files that are uploaded. Files are encoded and transmitted in the content body using
multipart MIME format with an HTTP Content-Type header. ASP.NET extracts this
information from the content body into individual members of an HttpFileCollection.

The ‘HttpPostedFile’ class provides methods and properties to access the contents and
properties of each file. In our case, we use this class to check the length, name and type of
the file.

That’s it. Click on the ‘Browse’ button to upload a file, one at a time. To upload more than
one file, click on the Browse button again and select the file you would like to upload. For
demonstration purposes, I have selected five .jpg files.

If you desire to restrict file types or specify the maximum number of files that can be
uploaded, check these examples.

It’s also quite simple to remove a selected file from the list. Just click on the cross ‘x’ to the
left of each file. For eg: We will remove DesertLandscape.jpg by clicking on the cross ‘x’.
Once you have finally decided upon the files to be uploaded, click on the ‘Upload All’ button
to upload the files to the server. After the upload, a message will be displayed to the user
as shown below:

Note: There could be some issues related to permissions, filesize etc. while uploading files
on a server. I have highlighted some issues and their possible solutions in the section Some
important points to consider while uploading

I hope this article was useful and I thank you for viewing it. The entire source code of this
article can be downloaded over here.

Smooth Cascading Effect with ASP.NET Panels using


jQuery

Sometime back, I had written an article on Creating a Cool UI effect on ASP.NET Panels
using jQuery. A dotnetcurry.com visitor, Musez wrote back asking if the effect could be
automated, creating it like a cascading effect. The cascading effect here would be described
as follows - When the open button is clicked, all the panels fade and slide one after the
other, creating a smooth cascading effect. Similarly, when the close button is clicked, the
panels slide back to their original position. Achieving such a feature is relatively simple in
jQuery and I will demonstrate that in this article.

Feature Description: The user will have control over showing and hiding panels, on the click
of a button. To start off with, only a ‘+’ image button will be visible in the header panel.
When the user clicks on this button, all the panels will be made visible creating a sliding
effect, one at a time. Similarly all the panels will slide and hide when the user clicks on the
‘–‘ image button again. Let us see how to achieve this effect.

I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead,
I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide.
Please do take a note that this example uses jQuery’s current version - jQuery 1.3.2 and
jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.

Step 1: Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’
from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the
Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.

Step 2: Download jQuery 1.3.2 and jQuery VS 2008 Doc. Create a ‘Scripts’ folder in the
Solution Explorer of your project and add these files to this folder.

Assuming you have downloaded these files, create a reference to these files in the <head>
section of your page as shown below:

<head runat="server">
<title>jQuery ASP.NET Panel Cascading</title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
</head>

Note: If you are using MasterPages, check out my article on how to Use jQuery in
MasterPages

Step 3: Now add a Header and a few Body panels to the page. I have also added an
Images folder which contains images for ‘Show’ and ‘Hide’ buttons, as shown below:

<body>
<form id="form1" runat="server">
<div>
<div class="cpHeader">
<asp:ImageButton ID="btnShow" ImageUrl="~/Images/Show.gif"
runat="server" OnClientClick="return false;" />
<asp:ImageButton ID="btnHide" ImageUrl="~/Images/Hide.gif"
runat="server" OnClientClick="return false;" />
</div>

<asp:Panel ID="Panel1" runat="server" class='cpBody'>


<asp:Label ID="Label1" runat="server" Text="Label">Panel 1
Content</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" class='cpBody'>
<asp:Label ID="Label2" runat="server" Text="Label">Panel 2
Content</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" class='cpBody'>
<asp:Label ID="Label3" runat="server" Text="Label">Panel 3
Content</asp:Label>
</asp:Panel>

</div>
</form>
</body>

Step 4: Observe that we have set the CssClass on the header and body panels to add some
styling to the controls. The CSS will look similar to the following:

<head runat="server">
<title>jQuery ASP.NET Panel Cascading</title>
<style type="text/css">
.cpHeader
{
color: white;
background-color: #719DDB;
font: bold 11px auto "Trebuchet MS", Verdana;
font-size: 12px;
cursor: pointer;
width:450px;
height:18px;
padding: 4px;
}
.cpBody
{
background-color: #DCE4F9;
font: normal 11px auto Verdana, Arial;
border: 1px gray;
width:450px;
padding: 4px;
padding-top: 7px;
}
</style>

...

Step 5: The final step is to add the Cascading UI effect to the Panels.

Add the following jQuery:

...

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {

$("div.cpBody").hide();
$("#btnHide").hide();
var panelArray = $('div.cpBody').length;
var temp = -1;

$("#btnShow").click(function displayPanel() {
if (temp < panelArray) {
$('div.cpBody').eq(++temp).fadeIn(2000, function() {
displayPanel();
if (temp == panelArray) {
$("#btnHide").show();
$("#btnShow").hide();
}
});
}
});

$("#btnHide").click(function hidePanel() {
if (temp >= 0) {
$('div.cpBody').eq(--temp).fadeOut(2000, function() {
hidePanel();
});
if (temp < 0) {
$("#btnHide").hide();
$("#btnShow").show();
temp = -1;
}
}
});

});
</script>

Shown above is a recursive function that loops through the panels (with cssClass=’cpBody’)
and creates a fading effect using the fadeIn() fadeOut() methods. To start with, all the
panels are hidden by using $("div.cpBody").hide(). Then using the variables panelArray
and temp, we recurse through the displayPanel() function on the click of a
button(btnShow), displaying each panel one at a time using the fadeIn() function.

Similarly, we do a reverse lookup to hide the panels on the btnHide click, using the
fadeout() function.

CAUTION: After wasting a couple of hours, I discovered that by mistake, I had added
a reference to the jQuery Visual Studio Intellisense doc jquery-1.3.2-vsdoc2.js file. Due
to this, the fadeIn() and fadeOut() was not working as expected on Mozilla3 and
Crome. You do not need to add a reference to this jQuery intellisense doc file in your
markup since Visual Studio automatically picks it up if it is in the same directory as that of
the jQuery file. Edit: Thanks to Alex for that tip as I had completely forgotten about the
same.

On running the application, when the user clicks the ‘+’ button, the panels appear one by
one

Similarly on clicking the ‘ – ‘ button, the panels fade out to their original position creating a
cool UI effect

Demo: The sample can be viewed live over here


http://www.dotnetcurry.com/Demos/jQueryCascade/

I hope this article was useful and I thank you for viewing it. The entire source code of this
article can be downloaded over here.

Using jQuery Validation in ASP.NET Master Pages

Sometime back, I had written an article on Using jQuery with the ASP.NET CustomValidator
Control. jQuery also has a Validation plug-in which is full of features and is quite flexible.
However the name mangling in ASP.NET Master Pages presents interesting challenges in
using this plug-in with it and I could not find a working solution on the net. In this article, I
will demonstrate how to use the jQuery Validation plug-in with Master Pages. This article
does not compare jQuery validation with ASP.NET Validation Controls, but has been written
with the intention of demonstrating how jQuery Validation can be used in ASP.NET.

Note: ASP.NET Validation controls runs on client as well as server side, and you should
‘always’ perform validation on server-side.

I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead,
I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide.
Please do take a note that this example uses jQuery’s current version - jQuery 1.3.2 and
jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.

jQuery Validation Plug-in

bassisstance.de has provided a cool jQuery Validation Plugin that has the following
features(only a few listed here):

- Standard validation methods for validating fields like emails, digits, date, URLs, credit card
numbers and much more.
- Hide and display error messages as needed
- Validation on Keyup, Blur, Submit button
- Flexibility in specifying validation rules

The plug-in runs client-side and suits most of the validation requirement; however there are
challenges while implementing it with an ASP.NET application. The challenge gets stronger
when we deal with ASP.NET Master Pages. We will see how.

When you are using a MasterPage, the ASP.NET runtime modifies a WebControl’s ClientID,
with each level of container prefixing its ID to the control, to ensure uniqueness. So for
example, a TextBox called ‘txtName’ gets rendered as ‘ctl00$ContentPlaceHolder1$txtName’
(assuming the container is ContentPlaceHolder1) as shown below:

<input name="ctl00$ContentPlaceHolder1$txtName" type="text


id="ctl00_ContentPlaceHolder1_txtName" />

Now the jQuery Validation plug-in relies on elements having a ‘name’ attribute. So
referencing a control using $('#<%= txtName.ClientID%>') doesn’t really work with jQuery
Validation plug-in. Instead what is needed is to use the controls ‘name’ attribute with the
jQuery Validation control. With the name mangling in ASP.NET Master Pages, here’s how to
solve the problem

Step 1: Create an ASP.NET website with a Master Page and a Content Page.
Step 2: Download jQuery 1.3.2, jQuery VS 2008 Doc and jQuery Validation plug-in. Create
a ‘Scripts’ folder in the Solution Explorer of your project and add these files to this folder.

Assuming you have downloaded these files, create a reference to these files in the <head>
section of your Master page as shown below:

<head runat="server">
<title>jQuery Validation in ASP.NET Master Page</title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>

<asp:ContentPlaceHolder id="head" runat="server">


</asp:ContentPlaceHolder>
</head>

Step 3: Now go to your ContentPage and add two Textboxes and a Button inside the
ContentPlaceHolder as shown below:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"


Runat="Server">
Name: <asp:TextBox ID="txtName" MaxLength="30" runat="server" /><br />
Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</asp:Content>

Step 4: Now inside this ContentPage, add the following script to enable jQuery Validation

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"


Runat="Server">
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
rules: {
<%=txtName.UniqueID %>: {
minlength: 2,
required: true
},
<%=txtEmail.UniqueID %>: {
required: true,
email:true
}
}, messages: {}
});
});
</script>

Name: <asp:TextBox ID="txtName" MaxLength="30" runat="server" /><br />


Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</asp:Content>

Since the jQuery Validation plug-in relies on elements having a ‘name’ attribute, observe
how we are using the UniqueID of the controls to reference them like <%=txtName.UniqueID
%> and apply validation rules to them.
Run the application and click on the Submit button. The Validation fires displaying the error
messages as shown below

On entering invalid data, the following message appears

If you want to display custom messages, make use of the ‘messages’ parameter to specify a
custom error message for a field as shown below:

<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
rules: {
<%=txtName.UniqueID %>: {
minlength: 2,
required: true
},
<%=txtEmail.UniqueID %>: {
required: true,
email:true
}
}, messages: {
<%=txtName.UniqueID %>:{
required: "* Required Field *",
minlength: "* Please enter atleast 2 characters *"
}
}
});
});
</script>

So as seen in the screenshot below, using the ‘messages’ parameter, the error message
‘This field is required’ gets replaced with ‘* Required Field’ . You can also add some css to
the error message as per your requirement.
That’s it for now. I hope you will now be able to use the jQuery Validation Plug-in with
ASP.NET Master Pages. More features about the jQuery Validation Plug-in can be learnt from
here.

I hope this article was useful and I thank you for viewing it. The entire source code of this
article can be downloaded over here.

Using jQuery with the ASP.NET CustomValidator Control

I have absolutely no hesitation in stating that jQuery is the most popular JavaScript and
AJAX framework available. Now-a-days, developers caught by this wave, tend to ease their
client-side development by using jQuery wherever and whenever they can. I came across a
similar requirement when one of my clients requested me a POC (Proof of Concept) of using
jQuery with the ASP.NET CustomValidator validation control. This article discusses how to
validate an Address field using the ASP.NET CustomValidator and jQuery.

I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead,
I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide.
Please do take a note that this example uses the latest version of jQuery 1.3.2 and jQuery
1.3.2 Visual Studio 2008 Autocomplete documentation.

A Brief note about the CustomValidator control


The CustomValidator control performs a field’s validation based on custom validation logic
that you provide. Using this control, you can write server-side validation code using C# or
VB.NET as well client-side validation code using JavaScript, to check user input.

Note: Always remember to perform server-side validation.

Since the focus of this article is to integrate jQuery and the ASP.NET CustomValidator
control, I will jump straight to the basics of ClientSide Validation with the CustomValidator
control. When we do client-side validation, the JavaScript function to be used looks similar
to the following:

function ClientSideValidation(source, args)

where ‘source’ is a reference to the validation control and ‘args’ is the object whose ‘Value’
property represents the data to be validated. The args.IsValid property determines if the
data validates (true) or does not validate (false).

The ‘ClientFunctionName’ property of the CustomValidator control associates your client-


side code with the CustomValidator.

Typically, this is how you would do Client-Side Validation using JavaScript

<asp:Textbox id="TextBox1" runat="server" text=""></asp:Textbox>


<asp:CustomValidator id="custV" runat="server"
ControlToValidate = "TextBox1"
ErrorMessage = "Minimum 4 characters required"
ClientValidationFunction="CheckLength" >
</asp:CustomValidator>

...

<script type="text/javascript">
function CheckLength(sender, args) {
args.IsValid = (args.Value.length >= 4);
}
</script>

</head>

Let us see how to do the same using jQuery.

Assuming you have downloaded the jQuery files stated in the beginning of this article,
create a reference to the jQuery 1.3.2 file in the <head> section of your page as shown
below:

<head runat="server">
<title>CustomValidator using jQuery</title>

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

Now drag and drop a TextBox, a Button control and the CustomValidator control to the
page. Set the TextMode=”Multiline” property of the TextBox to convert it to a <textarea>.
The TextBox will be used by users to enter ‘Address’ information. The requirement is that
the minimum characters to be entered in the TextBox should be 10, Maximum characters
should not exceed 50 and that the TextBox allows only AlphaNumeric characters along with
a few special characters like &().

Disclaimer: A CustomValidator control is used when the other ASP.NET validation controls
does not suit your needs. However the ‘Address’ field requirement described above, is
possible to achieve using the RegularExpression Validator control. Having said that, the
focus of this article is to just demonstrate how to use jQuery with the CustomValidator
control, and to be honest, I felt this example is a good candidate to demonstrate the code
brevity achieved using jQuery, while validating the Address field. Moving ahead…

After setting up a few properties on the CustomValidator control, the markup will look
similar to the following:

<asp:Label ID="Label1" runat="server" Text="Address : "></asp:Label>


<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"
CssClass='txtAdd'/>
<br />
<asp:CustomValidator ID="CustomValidator1" runat="server"
Display="Dynamic"
ErrorMessage="Field cannot be blank<br/>Minimum 10, Maximum 50 chars
allowed<br/>Only AlphaNumeric and Special Characters like &()- allowed"
ClientValidationFunction="chkAddressField"
onservervalidate="CustomValidator1_ServerValidate" >
</asp:CustomValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
C#
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
// Write your Server side validation code here.
}
VB.NET

Protected Sub CustomValidator1_ServerValidate(ByVal source As Object,


ByVal args As ServerValidateEventArgs)
' Write your Server side validation code here.
End Sub

Observe that the ClientValidationFunction is pointing to the chkAddressField() method. This


is the client-side Method that will check user input before the page is submitted. The server-
side method has been created but kept empty since that is not the focus of this article.

It’s time to introduce jQuery now. Write the following code in the <head> section of your
page

<head runat="server">
<title>CustomValidator using jQuery</title>

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
function chkAddressField(sender, args) {
args.IsValid = false;
$(".txtAdd").each(function() {
if (/^[A-Za-z0-9&()-]{10,50}$/.test(this.value)) {
args.IsValid = true;
}
});
}
</script>
</head>

In the code above, to start with, we are setting the args.IsValid property to ‘false’. The
property is set to ‘true’ only if the text entered in the textbox (with class ‘txtAdd’) passes
the regex validation.

If the user enters characters less than 10 or greater than 50 or a character that’s not
allowed, then the validation occurs at client side and prevents the user from submitting the
form as shown below

And that's it! Well I hope that gave you some idea of using jQuery with the CustomValidator
control. I will be sharing more examples with you as I continue exploring jQuery with
ASP.NET. Until then, happy coding! The entire source code of this article can be
downloaded from here
Creating a Cool UI effect on ASP.NET Panels using jQuery

In this article, we will see how to create a Cool UI effect on the ASP.NET Panels using
jQuery. In one my previous articles, I had discussed how to Create CollapsiblePanelExtender
Functionality using ASP.NET and jQuery. In this article, we will see how to create a Sliding
effect on a bunch of ASP.NET Panels. The user will have control over showing and hiding
panels, on the click of buttons. To start off with, only a ‘+’ and a ‘–‘ image button will be
visible in the header panel. A body panel will be made visible, one at a time, whenever the
user will click on the ‘+’ button. Similarly the panels will be hidden on each click of the ‘–‘
image button. Let us see how to achieve this effect.

If you are just getting started with jQuery, check this: Using jQuery with ASP.NET - A
Beginner's Guide. An updated version of jQuery is now available over here. If you have
been using version 1.2.6, replace it with the updated version.

Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the
templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution
Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.

Right click the Scripts folder > Add Existing Item > Browse to the path where you
downloaded the jQuery library (jquery-1.3.1.min.js) > Select the file and click Add.

Drag and drop the jquery-1.3.1.min.js file from the Solution Explorer on to your page
<head> to create a reference as shown below

Now add a Header and a few Body panels to the page. I have also added an Images folder
which contains images for Show and Hide as shown below:

<body>
<form id="form1" runat="server">
<div>
<div class="cpHeader">
<asp:ImageButton ID="btnShow" ImageUrl="~/Images/Show.gif"
runat="server" OnClientClick="return false;" />
<asp:ImageButton ID="btnHide" ImageUrl="~/Images/Hide.gif"
runat="server" OnClientClick="return false;" />
</div>

<asp:Panel ID="Panel1" runat="server" class='cpBody'>


<asp:Label ID="Label1" runat="server" Text="Label">Panel 1
Content</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" class='cpBody'>
<asp:Label ID="Label2" runat="server" Text="Label">Panel 2
Content</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" class='cpBody'>
<asp:Label ID="Label3" runat="server" Text="Label">Panel 3
Content</asp:Label>
</asp:Panel>
</div>
</form>
</body>

Observe that we have set the CssClass on the header and body panels to add some styling
to the controls. The CSS will look similar to the following:

<head runat="server">
<title>UI Effect with ASP.NET Panel</title>

<style type="text/css">
.cpHeader
{
color: white;
background-color: #719DDB;
font: bold 11px auto "Trebuchet MS", Verdana;
font-size: 12px;
cursor: pointer;
width:450px;
height:18px;
padding: 4px;
}
.cpBody
{
background-color: #DCE4F9;
font: normal 11px auto Verdana, Arial;
border: 1px gray;
width:450px;
padding: 4px;
padding-top: 7px;
}
</style>

The final step is to add some UI effects to the Panel.

Add the following jQuery:

...

<script type="text/javascript">
$(document).ready(function() {
var pan = $(".cpBody").hide();
var showNext = 0;
$("#btnShow").click(function() {
if (showNext < pan.length) {
$(pan[showNext++]).slideDown();
}
});

$("#btnHide").click(function() {
if (showNext > 0) {
$(pan[showNext - 1]).slideUp();
showNext--;
}
});

});

</script>
</head>

When you run the application, all the panels are hidden($(".cpBody").hide();).

On clicking the ‘+’ image button, the first panel is shown with a sliding effect.

Clicking the ‘+’ button shows the second panel and so on.

Similarly clicking on the ‘-‘ button hides the last visible panel

I hope you liked the article and I thank you for viewing it. The source code for this article
can be downloaded from here.

Some ASP.NET GridView UI Tips and Tricks using jQuery

This article demonstrates how to create simple UI effects in an ASP.NET GridView control
using jQuery. These tips have been tested in IE 7 and Firefox 3.

I assume you are familiar with jQuery. If not, please read my article over here before
continuing any further: Using jQuery with ASP.NET - A Beginner's Guide. Update - A new
version of jQuery has been released. jQuery 1.3.2 can be downloaded from over here:
Download Query 1.3

You can also check out my new EBook on using jQuery with ASP.NET called "51 Tips,
Tricks and Recipes with jQuery and ASP.NET Controls"
Set up an ASP.NET GridView as you usually do, binding it to a datasource. For
demonstration purposes, here’s some sample markup where I am using the Northwind
database and a GridView bound to the SQLDataSource to pull data from the database.

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


<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName],
[Address], [City] FROM [Customers]">
</asp:SqlDataSource>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CustomerID"
DataSourceID="SqlDataSource1" AllowPaging="False" AllowSorting="True"
>
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName"
SortExpression="ContactName" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City"
SortExpression="City" />
</Columns>
</asp:GridView>
</div>
</form>

The <connectionStrings> element in the web.config will look similar to the following:

<connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data
Source=(local);Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Note: In most of the tips shown here, I am using a complex jQuery row ‘filter’ suggested by
Karl Swedberg to a user in a jQuery forum. This filter is required due to the fact that a
GridView does not render (accessibility tags) a <thead> and a <tfoot> by default(read this
article of mine to learn how to make the GridView generate a <thead>). For the header, the
GridView generates <th>’s inside <tr>. Similarly for the footer, the GridView generates a
<table> inside a <tr> and so on. Hence it is required to use additional filters to exclude
header and footer rows while adding UI effects on the GridView. These tips have been tried
out on a GridView where paging is not enabled. When the paging is enabled, the pager
however gets highlighted. I am still working on a solution to prevent the UI effects from
being applied on the pager. I will update this article, once I find a solution. If you have a
solution that works cross browser, please share it with me.

The link to download the code for all these samples can be found at the end of this article.
Let’s see some tips.

1. Highlight an ASP.NET GridView row by clicking on it


This tip lets you highlight a row when you click anywhere on the row. Clicking back on a
highlighted row, removes the highlight.

<head id="Head1" runat="server">


<title>Highlight Row on Click</title>

<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$("tr").filter(function() {
return $('td', this).length && !$('table', this).length
}).click(function() {
$(this).toggleClass('currRow');
});
});
</script>

<style type="text/css">
.currRow
{
background-color:Gray;
cursor:pointer;
}
</style>

</head>

After applying the filter on the rows (to prevent the user from highlighting the Header and
Footer row), we use the toggleClass to highlight/remove highlight on the row.

Output:

2. Remove/Hide the Highlighted rows of an ASP.NET GridView


If you want to remove/hide the highlighted rows from the GridView, then here’s how to do
so. I have added a HTML button control (Button1) to the form

<input id="Button1" type="button" value="Remove Rows" />

The jQuery is as shown below:

<head id="Head1" runat="server">


<title>Hide Highlighted Rows>/title>
<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$("tr").filter(function() {
return $('td', this).length && !$('table', this).length
}).click(function() {
$(this).toggleClass('currRow');
});

$("#Button1").click(function() {
var hideRows = $("tr").hasClass("currRow");
if (hideRows == true) {
$("tr.currRow").remove();
}
});
});

</script>

<style type="text/css">
.currRow
{
background-color:Gray;
cursor:pointer;
}
</style>

</head>

Here the user first highlights the rows and then clicks on the ‘Remove Rows’ button to
remove the highlighted rows

3. Remove/Hide ASP.NET GridView Rows on Mouse Click


In our previous sample, we were following a two step process of first highlighting multiple
rows and then removing them. Let’s say if we want to remove the rows as the user clicks on
them, then follow this approach:

<script type="text/javascript">
$(document).ready(function() {
$("tr").filter(function() {
return $('td', this).length && !$('table', this).length
}).click(function() {
$(this).remove();
});
});
</script>
4. Highlight an ASP.NET GridView row on Mouse Hover
In case you do not want to define a separate style for the row and want to highlight a row
on mouse over (instead of the click), follow this tip:

<head id="Head1" runat="server">


<title>Highlight Row on Hover</title>

<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$("tr").filter(function() {
return $('td', this).length && !$('table', this).length
}).css({ background: "ffffff" }).hover(
function() { $(this).css({ background: "#C1DAD7" }); },
function() { $(this).css({ background: "#ffffff" }); }
);
});
</script>

</head>

Output:

5. Drag and Drop Rows of an ASP.NET GridView


This tip comes very handy when you are presenting a set of data in a GridView and want to
rearrange rows at runtime. I am using the Table Drag and Drop Plugin for this example and
it’s as simple as calling tableDnD() on the table. This plugin enables drag/drop on a table.

<head runat="server">
<title>Drag Drop Rows</title>

<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>


<script src="Scripts/jquery.tablednd_0_5.js"
type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$("#GridView1").tableDnD();
});
</script>

</head>

Output:
Before Drag

After Drop - dragging row with Customer ID ‘ANATR’ below ‘BLONP’

That’s it for now. We saw some UI tips that can be applied to an ASP.NET GridView using
jQuery. Stay tuned to see some more in the forthcoming articles. I am also planning to
write an article to store these UI changes when the user paginates through the Grid or a
postback occurs.

I hope you liked the article and I thank you for viewing it. The entire source code of this
article can be downloaded from here.

Creating CollapsiblePanelExtender Functionality using


ASP.NET and jQuery

I had recently written an article ASP.NET AJAX CollapsiblePanelExtender - Tips and Tricks
which showed how to use the ASP.NET AJAX CollapsiblePanelExtender control to easily add
collapsible sections to your web page. In this article, I will show you how to create a similar
functionality using jQuery with ASP.NET. Ever since I have been introduced to jQuery by
one of my colleagues Govind Kanshi (Microsoft), I have been experimenting with jQuery and
plan to share my work with my readers. This article is one such experiment that I did with
ASP.NET and jQuery.If you are just getting started with jQuery, check this: Using jQuery
with ASP.NET - A Beginner's Guide. Let us get started.

Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the
templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution
Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.
Right click the Scripts folder > Add Existing Item > Browse to the path where you
downloaded the jQuery library (jquery-1.2.6.js) and the intellisense documentation (jquery-
1.2.6-vsdoc.js) > Select the files and click Add.

Now drag and drop the jquery-1.2.6.js file from the Solution Explorer on to your page to
create a reference as shown below

Add two panel controls (<asp:panel >) to the page. Rename them to ‘pHeader’ and ‘pBody’
respectively.

<body>

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

<div>

<asp:Panel ID="pHeader" runat="server" CssClass="cpHeader">

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

</asp:Panel>

<asp:Panel ID="pBody" runat="server" CssClass="cpBody">

Lorem ipsum dolor sit amet, consectetur adipisicing elit,

sed do eiusmod tempor incididunt ut labore et dolore magna

aliqua. Ut enim ad minim veniam, quis nostrud exercitation

ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit

esse cillum dolore eu fugiat nulla pariatur

</asp:Panel>

</div>

</form>

</body>

</html>

Observe that we have set the CssClass on the two panels to add some styling to the
controls. The CSS will look similar to the following:
<head runat="server">

<title>Collapsible Panel Extender using jQuery</title>

<script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

<style type="text/css">

.cpHeader

color: white;

background-color: #719DDB;

font: bold 11px auto "Trebuchet MS", Verdana;

font-size: 12px;

cursor: pointer;

width:450px;

height:18px;

padding: 4px;

.cpBody

background-color: #DCE4F9;

font: normal 11px auto Verdana, Arial;

border: 1px gray;

width:450px;

padding: 4px;

padding-top: 7px;

</style>
The final step is to add collapsible behavior to the panels, similar to what the ASP.NET
CollapsiblePanelExtender provides.

Add the following jQuery:

<head runat="server">

<title>Collapsible Panel Extender using jQuery</title>

<script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function() {

$('#pHeader').click(function() {

$('#pBody').slideToggle('slow');

});

});

</script>

When the user clicks the header panel (pHeader), we run a function which toggles the
visibility of ‘pBody’ by adjusting its height in a ‘sliding’ manner. You can choose one of the
three predefined speeds: slow, normal or fast. The speed can also be defined by specifying
the number of milliseconds.

Run the application and click on the header panel to toggle the visibility of the panel body as
shown below:

On page load:

When the user clicks on the header panel to collapse the body(pBody):

pBody in a collapsed state


User clicks on the header panel to expand the body:

And that’s all is required to create a functionality similar to the CollapsiblePanelExtender.


Simple yet powerful! And that’s what jQuery is all about. I hope you liked the article and I
thank you for reading it.

Check/Uncheck all Items in an ASP.NET CheckBox List


using jQuery

The CheckBoxList control in ASP.NET provides a group of checkboxes that can be


dynamically generated by binding it to a data source. A few months ago, I had written a
similar article using ASP.NET and JavaScript over here Check/Uncheck all items in a
CheckBoxList using ASP.NET and Javascript . The approach we had taken using JavaScript
was, we first retrieved the checkboxlist control using document.getElementById(cbControl)
and then counted the number of <input> tags inside that control. Once we got the count,
we used a loop to set the state of each control.

In this article, we will explore how to use jQuery to select unselect all the checkboxes in an
ASP.NET CheckBoxList. If you are new to jQuery, check this: Using jQuery with ASP.NET - A
Beginner's Guide

Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the
templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution
Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.

Right click the Scripts folder > Add Existing Item > Browse to the path where you
downloaded the jQuery library (jquery-1.2.6.js) and the intellisense documentation (jquery-
1.2.6-vsdoc.js) > Select the files and click Add.

Now drag and drop the jquery-1.2.6.js file from the Solution Explorer on to your page to
create a reference as shown below

Drag and drop a CheckBoxList control to the page. Rename it to ‘cbList’.

<asp:CheckBoxList ID="cbList" runat="server">

</asp:CheckBoxList>
Now add items programmatically to the CheckBoxList by using the following code at the
Page load event:

C#

protected void Page_Load(object sender, EventArgs e)

if (!Page.IsPostBack)

cbList.Items.Add(new ListItem("Items 1", "Items 1"));

cbList.Items.Add(new ListItem("Items 2", "Items 2"));

cbList.Items.Add(new ListItem("Items 3", "Items 3"));

cbList.Items.Add(new ListItem("Items 4", "Items 4"));

cbList.Items.Add(new ListItem("Items 5", "Items 5"));

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

If (Not Page.IsPostBack) Then

cbList.Items.Add(New ListItem("Items 1", "Items 1"))

cbList.Items.Add(New ListItem("Items 2", "Items 2"))

cbList.Items.Add(New ListItem("Items 3", "Items 3"))

cbList.Items.Add(New ListItem("Items 4", "Items 4"))

cbList.Items.Add(New ListItem("Items 5", "Items 5"))

End If

End Sub

Now drag and drop a CheckBox from the toolbox to the page and rename it as ‘chkAll’. Now
if you observe the JavaScript solution in a previous article over here, I had to loop through
the checkboxes and then set its ‘checked’ property. Let us see how we can achieve this in
jQuery using 3 different jQuery approaches.

I have included all these approaches to show you how I reduced my code from Approach 1
to Approach 3
Approach 1: The longer approach

$("#chkAll").toggle(

function() {

$("input[@type='checkbox']").not('#chkAll').each(function
() {

this.checked = true;

});

},

function() {

$("input[@type='checkbox']").not('#chkAll').each(function
() {

this.checked = false;

});

});

});

Approach 2: Shortening the approach

<script type="text/javascript">

$(document).ready(function() {

$("#chkAll").toggle(

function() {

$('input[@type=checkbox]').attr('checked', 'true');

},

function() {

$('input[@type=checkbox]').removeAttr('checked');

});

});

</script>

Approach 3: Freezing it
<script type="text/javascript">

$(document).ready(function() {

$('#chkAll').click(

function() {

$("INPUT[type='checkbox']").attr('checked',
$('#chkAll').is(':checked'));

});

});

I liked the last approach which I got from here. In the code above, we are first assigning the
click event to the CheckBox(chkAll).

<script type="text/javascript">

$(document).ready(function() {

$('#chkAll').click(

When the user clicks the checkbox, we run a function which finds all elements of the
checkbox type and sets the ‘checked’ value of all items in the CheckBoxList to true or false
based on the checked value of the ‘chkAll’ checkbox.

If you have multiple checkboxlist on your page, you can pass the CheckBoxList name and id
as a parameter to the jQuery function as shown here:

$("INPUT[@name=" + name + "][type='checkbox']").attr('checked', $('#' +


id).is(':checked'));

The entire code with the finalized approach (Approach 3) will look similar to the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head runat="server">
<title>Check/Uncheck All CheckBoxes Using JQuery</title>

<script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function() {

$('#chkAll').click(

function() {

$("INPUT[type='checkbox']").attr('checked',
$('#chkAll').is(':checked'));

});

});

</script>

</head>

<body>

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

<div>

<asp:CheckBox ID="chkAll" runat="server" Text="Check All" /><br />

<asp:CheckBoxList ID="cbList" runat="server">

</asp:CheckBoxList>

</div>

</form>

</body>
</html>

On running the application, you get a screen similar to the following:

On clicking the CheckAll checkbox, all the checkboxes gets selected, similar to a gmail
application

On clicking the CheckAll checkbox again, the checkboxes gets unselected.

I hope you liked the article and I thank you for viewing it.

If you liked the article, Subscribe to my RSS Feed or Subscribe Via Email

Using jQuery with ASP.NET - A Beginner's Guide

Did you hear about jQuery.. NO...? It’s fantastic!! Well if you have been hearing those
words more too often from your colleagues but haven’t had the chance to explore jQuery
yet, then here’s this beginner guide for you to get started with jQuery and ASP.NET.

Update: I have written an EBook on using jQuery with ASP.NET Controls. It's called "51
Tips, Tricks and Recipes with jQuery and ASP.NET Controls".

Ok, the million dollar question - What is jQuery anyways?


jQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many
browsers. The jQuery framework is extensible and very nicely handles DOM manipulations,
CSS, AJAX, Events and Animations.

What is the difference between JavaScript and jQuery?


JavaScript is a language whereas jQuery is a library written using JavaScript.

Where can I download jQuery?


The latest version of jQuery as of this writing is jQuery 1.2.6 and can be downloaded from
here. [Update] An updated version of jQuery 1.3.2 has been released. jQuery 1.3.2 and
jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation. So whereever you see 1.2.6
mentioned in the rest of this article, just replace it with 1.3.2.

What has Microsoft got to do with jQuery?


In ScottGu’s blog, there was an announcement made a few weeks ago that Microsoft will be
partnering with the jQuery team and shipping jQuery with Visual Studio in future. Also,
jQuery intellisense annotation support will be available as a free web-download. Barely a
few weeks after the announcement, Microsoft during the PDC event (held in the last week of
October), announced that Visual Studio 2008 now supports jQuery Intellisense through an
additional file available from jQuery. This file can be downloaded from here. For those
interested, the release notes can be found here 1.2.6 (Release Notes).

A few days ago, Microsoft also released a VS2008 SP1 Hotfix to support all JavaScript files
including jQuery intellisense for Visual Studio 2008. Note that this hotfix works only if you
have VS 2008 with SP1 or Visual Web Developer Express Edition with SP1. You can
download the Hotfix from here (Downloads tab).

Checking out jQuery Intellisense in Visual Studio 2008 with SP1


Assuming you have installed the hotfix , downloaded the jQuery library and the jQuery VS
2008 IntelliSense documentation, follow these steps to move ahead.

Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the
templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution
Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.

Right click the Scripts folder > Add Existing Item > Browse to the path where you
downloaded the jQuery library (jquery-1.2.6.js) and the intellisense documentation (jquery-
1.2.6-vsdoc.js) > Select the files and click Add. The structure will look similar to the
following:

Now drag and drop the jquery-1.2.6.js file from the Solution Explorer on to your page to
create a reference as shown below

Note: Since you have applied the hotfix, you do not have to manually add a reference to
the jquery-1.2.6-vsdoc.js file in your page. Once the reference to the runtime library has
been added, Visual Studio automatically searches for the ‘vsdoc’ file and loads it. You just
need to keep both the runtime library and the documentation file next to each other.

To test intellisense, add a <script> block and key in ‘$(‘. You will get an intellisense similar
to the one shown below:
Show me some examples
This article would be incomplete without examples. So let us quickly see some.

Example 1 – Display an alert on asp:Button click using jQuery

Add a Button element to the page as shown below:

<asp:Button ID="Button1" runat="server" Text="Button" />

Now in order to tell the browser to perform some action using jQuery as soon as the
document is ready or loaded, use this block:

<script type="text/javascript">

$(document).ready(function() {

// add code here

});

</script>

Add your code in the function block

<script type="text/javascript">

$(document).ready(function() {

$("#Button1").click(function() {

alert("Hello world!");

});

});

</script>

On clicking the button, you get an alert code similar to the following:

Example 2: Demonstrating some animation on button click using jQuery

Our first example was a simple ‘Hello World’ example to keep up with the tradition while
introducing a new language. Let us enhance our sample and display some animation using
jQuery. We will animate an <asp:Panel> on a button click when the page loads. This sample
is loosely based on the demo over here:

To do so, add a HTML button and a <asp:Panel> to the page as shown below:

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

<input id="btnAnimate" type="button" value="Animate" />

<asp:Panel ID="Panel1" runat="server">

Some sample text in this panel

</asp:Panel>

</form>

Also add some css to beautify the div (remember asp:Panel renders as a <div>). The
<style> tag has been kept in the <head> element of the page.

<style type="text/css">

div {

background-color:#D5EDEF;

color:#4f6b72;

width:50px;

border: 1px solid #C1DAD7;

</style>

Finally add the jQuery code to animate the panel on button click. We would be using the
‘animate’ function. Observe how the intellisense helps us out with the parameters

After adding in the parameters for the animate() function, the complete code will look
similar to the following:

<script type="text/javascript">

$(document).ready(function() {

$("#btnAnimate").click(function() {

$("#Panel1").animate(
{

width: "350px",

opacity: 0.5,

fontSize: "16px"

}, 1800);

});

});

</script>

Here the animation occurs while changing the width, opacity and font properties of the
Panel when the button is clicked. The value ‘1800’ represents the number of milliseconds to
run the animation.

Run the sample and see the Panel getting animated as shown below:

Well that’s it for an introduction. Remember that this article is only an introduction and in
no way demonstrates the capabilities of jQuery. I have written an EBook which
demonstrates the capabilities of doing client side development in ASP.NET using jQuery. It's
called "51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls". In the
forthcoming articles, we will see how jQuery can further be used with ASP.NET and AJAX.

If you liked the article, Subscribe to my RSS Feed.

Vous aimerez peut-être aussi