Bean Software Logo
ASP.NET Database Search Control
 Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Using jQuery With ASP.NET

What is jQuery?

jQuery is a cross browser JavaScript library that helps to traverse through HTML elements, event handling, effects(animation) and Ajax interactions.
It is very easy to learn and implement.

We will see how to work on jQuery with asp.net and few of jQuery features in this article.

 

Using jQuery in ASP.NET Page

First of all you will require to link jQuery library to your ASP.NET page. Use below shown code in HTML code to include latest jQuery.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"> 
        </script>

It also can be achieved using server ASP.NET side code like this:

protected override void Render(HtmlTextWriter writer)
{
    this.Page.ClientScript.RegisterClientScriptInclude("jQuery", "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");
    base.Render(writer);
}

To run any function on page load ASP.NET has inbuilt method to register startup script. Below shown example will run javascript function "helloWorld" on page load which appends text "Hello World!!" in the div with id "divSample"

Example:

HTML code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>jQuery with asp.net examples - HelloWorld with jQuery</title>
 
    <script type="text/javascript">
    function helloWorld()
    {
        $("#divSample").append("Hello World!!");
    }
    </script>
 
</head>
<body>
    <form id="form2" runat="server">
        <div id="divSample">
        </div>
    </form>
</body>
</html>

C# Server-side code:

protected override void Render(HtmlTextWriter writer)
{
    this.Page.ClientScript.RegisterClientScriptInclude("jQuery",
        "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");
    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(),
        "startup", "<script type=\"text/javascript\">helloWorld();</script>");
    base.Render(writer);
}

Go to jQuery "Hello World" Demo page

Now you have idea how to include jQuery in ASP.NET page and run script on page load. We will see how to pass data to server and get response from server dynamically using jQuery in sections "Ajax using jQuery" and "jQuery Ajax with JSON"

No we will see few of the jQuery features that are easy to learn and implement with ASP.NET.

jQuery Selectors

Selectors are most useful feature in jQuery, Selectors helps to select element(s) in an HTML document.

jQuery has large number of options for selectors, you can select an element or array of elements by its ID, tag name, class name, with particular attributes. There are lots options to traverse through parent and children to find out an element.

Every selector returns an array of elements rather than single element; I feel this is a very helpful feature in jQuery while working with jQuery.

Userful Selectors Examples:

$("#selectDiv") //will return an array containing element which has id = selectDiv

$("div") //will return an array containing all "div" elements.

$(".header") //will return an array containing elements which has class name = header

$("input[name='emailaddress']") //will return an array containing "input" elements which has name = emailaddress

Go to jQuery Selectors Demo page to see this live.

There are lots of such selectors available in jQuery to help developers. You can check out more of them here: http://docs.jquery.com/Selectors

jQuery Chainability

It's a magical concept in jQuery to make code short and simple. Every jQuery method returns query object itself so it will allow performing function on it and maintaining a chain.

Example:

$("div").addClass("sample").html("html changed").show();

This code will add class "sample" to all divs, will replace its inner HTML with "html changed" and make all divs visible.

jQuery Object Accessors

Object accessors can be used on returned object from any of jQuery selector. The most useful method is each; it will help to loop through every element matched by selector and execute a function with context of this element.

Example:

If we want to place JavaScript confirm message on click of delete link in a grid, assume this link contains class "removeItem"

$(". removeItem").each{function()
{
    $(this).bind("click",
        return confirm("Are you sure you wish to delete this item?"));
}

Go to jQuery Object Accessors Demo page to see this sample live.

jQuery Events

jQuery has great collection of event related helpers, you can check them out here http://docs.jquery.com/Events. For event handling, bind and unbind is most usable methods.

Example:

$("p").bind("click", function()
{
  $(this).append("clicked");
});

This code will add onclick event handler to all paragraphs in document and on click of them will append text "clicked" to the clicked paragraph

function clickMe()
{
    $("#debugDiv").append("clicked!");
}

$("p").bind("click",clickMe); // Will bind clickMe function on click event of paragraphs

$("p").unbind("click",clickMe); // Will unbind clickMe function on click event of paragraphs

jQuery has document ready event which helps to run methods when DOM is ready to be traversed and manipulated.

$(document).ready(function()
{
   $("p").append("This text appended on DOM ready");
});

This will append "This text appended on DOM ready" to paragraphs available in document when DOM is ready.

Go to jQuery Events Demo page to see this example live.

For more details on DOM ready please visit: http://docs.jquery.com/Events/ready#fn

Ajax using jQuery and ASP.NET

Ajax with jQuery is really simple to achieve. There are enough options to get asynchronous reply from server with jQuery Ajax.

"load" method is a simplest form of jQuery Ajax, It will load html content in document element returned from server

Example of jQuery Ajax load method:

$("#serverResponse").load("AjaxCall.aspx"); // Response from page AjaxCall.aspx will get loaded in
// Div "serverResponse" Send data to the server using jQuery Ajax Example:
           
$.get("AjaxCall.aspx" // Call page AjaxCall.aspx
,{name: $("#txtName").val()} //Pass querystring "name" with value of text box "txtName"
,function(data) // On successfully retrival of response
{
      $("#serverResponseSendData").html(data); // Apply recevied html response to html of div "serverResponseSendData"
});

Go to jQuery Ajax Demo page to see it live.

jQuery Ajax with JSON data

JSON(Javascript Object Notation) is great form of data to transfer in an Ajax call, Please visit http://json.org for more details on JSON.

There are lots of free code and libraries available for asp.net to generate JSON data. Json.Net is one among them.

I've created simple method using Json.Net which will return JSON representation of a datatable.

public static string datatableToJSON(DataTable dt)
{
    StringBuilder jsonStringBuilder = new StringBuilder();
    StringWriter jsonStringWriter = new StringWriter(jsonStringBuilder);
 
    JsonWriter jsonWriter = new JsonTextWriter(jsonStringWriter);
 
    if (dt != null && dt.Rows.Count > 0)
    {
        jsonWriter.Formatting = Formatting.None;
 
        jsonWriter.WriteStartArray();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonWriter.WriteStartObject();
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonWriter.WritePropertyName(dt.Columns[j].ColumnName.ToString().ToLower());
                jsonWriter.WriteValue(dt.Rows[i][j].ToString());
            }
            jsonWriter.WriteEndObject();
        }
        jsonWriter.WriteEndArray();
 
        return jsonStringBuilder.ToString();
    }
    else
    {
        return null;
    }
}

Now we will try to parse this JSON data and build a grid out of this data at client side.

It is really simple task using jQuery:

$.ajax({type:"POST", // jQuery ajax with POST method
    url: "JSONCall.aspx", // Call page JSONCall.aspx
    success:function(serverResponseData) // On success call function
    {
        dtItems = eval("(" + serverResponseData + ")"); // evaluate retrived data to javascript object
       
        var htmlGrid = "";
       
        htmlGrid += "<table cellspacing=\"0\" cellpadding=\"4\" border=\"0\" class=\"grid\"><tr class=\"gridHeader\"><th scope=\"col\">Index</th><th scope=\"col\">Item Code</th><th scope=\"col\">Price</th></tr>";
       
        for(var i=0;i<dtItems.length;i++) // traverse through items in this object
        {
            var rowClass = (i%2 == 0) ? "gridRow" : "gridRowAlternate";
            htmlGrid += "<tr class=\""+rowClass+"\"><td>"+dtItems[i].index+"</td><td>"+dtItems[i].itemcode+"</td><td>"+dtItems[i].price+"</td></tr>";
            // Build grid from retrived data in current item
        }
       
        htmlGrid += "</table>";
       
        $("#divJSONGrid").html(htmlGrid); // apply created grid HTML to a div "divJSONGrid"
    }
    }); 

Go to jQuery Ajax JSON Demo page to see this example live.

Effects with jQuery

jQuery has inbuilt effect methods. Show, hide, slideDown, slideUp, toggle, fadeIn, fadeOut, animate etc. are few of them. Almost effect method has parameter for duration and callback function, callback function will get called after finishing an animation of effect.

jQuery Effects Example:

$('#divSample').hide(1000); // will hide the div "divSample", and it will animate for 1000 miliseconds
 
$('#divSample').show(1000); // will show the div "divSample"
 
$('#divSample').toggle (1000); // will toggle display of the div "divSample"

jQuery allow us to create our own animation using "animate" method:

$("#divSample3").animate( // will animate the div "divSample"
   // to height 200px, width 400px and opacity of .5, for 1000 milisecond
{height:200, width:400, opacity: .5}, 1000, function()
{
   alert("Animation complete!"); // call method on completion of animation
});

Go to jQuery Effects Demo page to see this effects live.

There are lots of thing in jQuery which I could not cover in this article, I recommend you to visit http://jquery.com/ and http://docs.jquery.com/Main_Page to learn more about jQuery.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google


comments powered by Disqus

Related articles:

1. How To Create Your Own Http Module.
2. What is .NET Framework?
3. A Gentle Intro To jQuery in ASP.NET