Tuesday, November 25, 2008

JQuery and ASP.Net

Recently I had to built an online art gallery for an artist (still to be deployed :( ). The site is relatively small, from a menu a user can select a group of pictures (gallery) and these images are loaded into a JQuery carousel.

JQuery is a great lightweight JavaScript library and nowadays there are plenty of plugins out there to use. This is a great link for JQuery plugins.

In this little site I used a bunch of plugins, ThickBox, JCarousel and so on.

I used AJAX to wire the server side ASP.NET to the client side code.
Follow these steps to use AJAX and ASP.NET:

1. Create a WebMethod in the page:


[System.Web.Services.WebMethod()]
public static List GetGalleryImages(int galleryID)
{
return galleryService.GetGalleryImages(galleryID);
}


In this case, galleryID is a parameter passed from the client side and it returns a list Picture objects. Picture is a simple POCO populated from an XML file in my case.

2. In a JS here is the code that does the XMLHttpRequest call to the GetGalleryImages WebMethod:


function LoadGalleryImages(galleryID){
$.ajax({
type: "POST",
url: "default.aspx/GetGalleryImages",
data: "{'galleryID': '" + galleryID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status) {
LoadCarousel(msg.d);
},
error: function(xhr,msg,e){
alert("Server error, pls try again!");
}
});
}


Note that JSON is used to pass and return data. Parameters are passed as name/value array. LoadCarousel() is a simple JavaScript method to populate the JQuery Carousel.
The list of pictures is returned in msg.d

That's it, hope you find this approach useful. With this approach one can build rich sites using the power of JQuery, use domain objects to manage the business rules of the site and use the code behind of the page as a 'controller'. I didn't use the new ASP.NET MVC. For a one page web site I think its an overkill.

No comments:

Post a Comment