jQuery and ASP.NET

Share this article

Introduction

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", "https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");
    base.Render(writer);
}

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”



    jQuery with asp.net examples - HelloWorld with jQuery

    
    function helloWorld()
    {
        $("#divSample").append("Hello World!!");
    }
    



    
        
        
    

C# Server-code:

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

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.
Example:

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

jQuery Object Accessors

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

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

jQuery Events

Example:

$("p").bind("click", function()
{
  $(this).append("clicked");
});
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
$(document).ready(function()
{
   $("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.
Example:

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

        jsonWriter.WriteStartArray();
        for (int i = 0; i IndexItem CodePrice";

        for(var i=0;i"+dtItems[i].index+""+dtItems[i].itemcode+""+dtItems[i].price+"";
            // 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.
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"
$("#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
});
Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week