JQuery and ASP.NET page methods

What?

jQuery is a lightwight javascript library loaded with really amazing features and UI richness that cannot be ignored instantly. It provides fast and easy way of HTML DOM traversing and manipulation, event handling, client side animations, etc.You can perform routine javascript tasks with jQuery but the difference is that jQuery is easy to use and give too much flexibility to the developers.

The definition mentioned in jQuery official Web Site

“jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript”

From Scott Gu

“One of the characteristics of jQuery commands is that they can be “chained” together – so that the result of one command can feed into another.  jQuery also includes a built-in set of animation APIs that can be used as commands.  The combination allows you to do some really cool things with only a few keystrokes.”

Features of jQuery

Here are the famous features of jQuery.

Effects and animations
DOM element selections functions
DOM traversal and modification
Events
CSS manipulation
Ajax
Extensibility
Utilities – such as browser version and the each function.
JavaScript Plugins

As mentioned in the above features jQuery is used in web application to handle events, validation, adding effects and animation, client side processing and many more.

Compatible languages

jQuery can be used almost with any web development languages ranging from ASP, ASP.NET,PHP, CGI,Servlets, CGI etc. Ofcourse you can create some appealing and interactive webcontent by blending it with plain HTML.

Using with ASP.NET and Visual Studio

Being a Microsoft shill I would like to write more specifically about using it with ASP.NET and Visual Studio. To start building ASP.NET download the latest jQuery version 1.3.2 at the time of writing from here (common script file for all languages) and place it in a new folder say scripts under the root of your web application. Folder part is optional but a good practice in terms of managing resources like images, CSS, script files etc.

Note: The download page has another link for Visual Studio which you should prefer as it contains intellisence support for writing javascripts. Here is a link to it jQuery for VisualStudio

Before doing any magic with jQuery we need to make sure that we start adding events etc. as soon as the DOM is ready by doing

$(document).ready(function() {
// do stuff when DOM is ready
});

Although we can append our script within the head tag like

<head runat=”server”>
<title></title>
<script src=”scripts/jquery-1.3.2-vsdoc2.js” type=”text/javascript”></script>

<script type=”text/javascript”>
$(document).ready(function(){
alert(“Welcome to jQuery”);
});

</script>
</head>

but again for clear understanding I will place my full example script in another file say Default.js and reference it in head tag.

For this example I will update a div with the result returned from a page method named HelloQuery in default.aspx code behind file which will take a name from the ASP textbox control and display Hello + name in Result div.

Secondly a div DateDiv will be updated with server time by calling GetDate pageMethod.

Writing a page method is easy just add [WebMethod] attribute found in System.Web.Services on top of standard static method like

[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToShortDateString();
}
}

Default.aspx

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
<script src=”scripts/jquery-1.3.2-vsdoc2.js” type=”text/javascript”></script>
<script src=”scripts/Default.js” type=”text/javascript”></script>
</head>
<body>

<form id=”form1″ runat=”server”>
<div>
<h2> Calling ASP.NET Page Method with jQuery </h2>
<p>Enter your name:</p>

<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
<input id=”btnSubmit” value=”Say Hello” type=”button”  />

<div id=”Result” style=”padding:20px 20px 20px 0; color:Navy; font-size:22px”></div>

<div id=”DateDiv” style=”padding:20px 20px 20px 0; color:Navy; font-size:22px”>Click Me for Time</div>

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

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static string HelloQuery(string name)
{
return “Hello ” + name;
}

[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToShortDateString();
}
}

Default.js

$(document).ready(function() {
$(“#btnSubmit”).click(function() {
$.ajax({
type: “POST”,
url: “Default.aspx/HelloQuery”,
data: “{‘name’: ‘” + $(‘#txtName’).val() + “‘}”, // “{‘name is the parameter name passed to HelloQuery page method
contentType: “application/json; charset=utf-8″,
dataType: “json”,
success: function(msg) {
// Replace the div’s content with the page method’s return.
$(“#Result”).text(msg.d);

}
});
event.preventDefault();
});
});

$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$(“#DateDiv”).click(function() {
$.ajax({
type: “POST”,
url: “Default.aspx/GetDate”,
data: “{}”,
contentType: “application/json; charset=utf-8″,
dataType: “json”,
success: function(msg) {
// Replace the div’s content with the page method’s return.
$(“#DateDiv”).html(msg.d);
}
});
});
});

Download sample project

From Where I can get jQuery Library?

The jQuery library is freely available on jQuery official web site (www.jquery.com). Detail documentation, tutorials are also available to learn about jQuery.

Conclusion

PageMethods provides a solution for the limitations of the standard way of handling pages, URLs and parameters.
The usual way to proceed is not structured. With PageMethods, the code of your pages is simpler, cleaner and more reliable. The approach is based on strict page inputs and declarative parameter binding. With PageMethods, each page exposes a set of methods that represent the different ways to call the page.
All you have to do to start benefiting from sharp URLs is to add methods to your pages, and mark these methods with attributes provided by PageMethods.

This project of 3 files mainly the Default.aspx, Default.aspx.cs and Default.js. This is just a limited demo of functionality offered by jQuery and ASP.NET but to start with its good.