jQuery and ASP.NET

By Sam Deering


Using jQuery in ASP.NET is not that complex. Just follow these steps and you should achieve our main goal here. Use the HTML code below to include jQuery.

Or you can use ASP.NET server side code like this:

protected override void Render(HtmlTextWriter writer)
    this.Page.ClientScript.RegisterClientScriptInclude("jQuery", "");

To execute any function on page load, ASP.NET has inbuilt method to register startup script. The code below will run javascript function “helloWorld” on page load which appends text “Hello World!” inside div with id “divSample”




C# Server-code:

protected override void Render(HtmlTextWriter writer)
        "startup", "");

Now you’ve got the idea on how to put jQuery inside ASP.NET page and run script on page load.
We’ll see how to pass data to server and get response from it dynamically using jQuery.

jQuery Selectors

This is the most useful feature in jQuery. This helps select elements in a HTML document.
jQuey has lots of options for selectors, you can select an element or array of elements by its ID, tage name, class name, with particular attributes.
Useful Selector 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

jQuery Chainability

It’s a great concept in jQuery to make code short and simple. In every jQuery method, it returns query object itself so it’ll allow performing function on it and maintain a chain.

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

jQuery Object Accessors

This can be used on returned object from any of jQuery selector.

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

jQuery Events


$("p").bind("click", function()
function clickMe()

$("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
   $("p").append("This text appended on DOM ready");

Ajax using jQuery and ASP.NET

Ajax with jQuery is not that hard to achieve. There are some options to get asynchronous reply from server with jQuery Ajax.
“load” method is the most simple form of jQuery Ajax.

$("#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"

jQuery Ajax with JSON data

Javascript Object Notation or JSON is a great form of data to transfer in an Ajax call.

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;

        for (int i = 0; i < dt.Rows.Count; i++)
            for (int j = 0; j < dt.Columns.Count; j++)

        return jsonStringBuilder.ToString();
        return null;

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

$.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 += "";

        for(var i=0;i";
            // Build grid from retrived data in current item

        htmlGrid += "";

        $("#divJSONGrid").html(htmlGrid); // apply created grid HTML to a div "divJSONGrid"

Effects with jQuery

jQuery has its built it effects such as show, hide, slideDown and stuffs like that. Effect method has parameter for duration and callback function. This will get called after finishing an animation effect.

$('#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"
$("#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
  • Nikhil

    Awesome Info!!! Thanks for sharing..:)



Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.

IndexItem CodePrice