Dot Net Perls

Page_Load Event and AJAX in ASP.NET

by Sam Allen - Updated April 29, 2009
Arrow

Problem. You want to use ASP.NET code-behind and the Page_Load event with AJAX in a working program. Here we implement AJAX with code-behind. The browser sends messages to the server, and the ASP.NET code-behind responds to them. Solution. Here we look at how you can make simple AJAX calls and ASP.NET work together.

1. Using AJAX in ASP.NET

When you create a new AJAX or ASP.NET page, it will have a Page_Load function in the code behind file. This is run each time a POST or GET message is sent to it. Your .aspx page can be conditional, returning either the whole page's starting markup file, or any data it wants to in response to an XMLHttpRequest.

<script type="text/javascript">
var request;

// A
// Here is the new function that is called when the user submits the form.
// This example uses POST.
function submitCallback() {
    var inputValue = document.getElementById("SearchInput").value;
    var sendStr = "name=" + inputValue;
    request = new XMLHttpRequest();

    // B
    // Specify the POST method and send it.
    request.open("POST", "Default.aspx");
    request.onreadystatechange = readyCallback;
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRequestHeader("IsLookup", "true");
    request.send(sendStr);
}
</script>

Note on the example. The examples here use the HTTP POST action, but you may want to use GET, which I show further down. Make a custom function that is activated by the user clicking or whatever. Here is the JavaScript, which you can put in the <script> block.

Steps in the code. A. submitCallback takes the value of SearchInput. The input is simply a regular HTML element with an ID in the page. Note that it has a real HTML ID and not an ASP.NET server ID. submitCallback builds a special string for the server that contains "name=" at the front.

Next steps. B. It uses XMLHttpRequest. submitCallback sets up the XMLHttpRequest. XMLHttpRequest uses a POST to the current page, Default.aspx. XMLHttpRequest content type is set to a standard format. Request is posted.

Header note. A special header is sent with the POST request to the Default.aspx page. This header can be called anything—I use the key "IsLookup". The value can be set to something like "true". This tells the aspx .cs file that this is a special IsLookup request.

2. Example of Page_Load in C#

Here we look into Page_Load in the code-behind file of this page. This code is in C#. The Page_Load method is always executed, even in POST requests. After the code there is an explanation.

// This is part of the C# code-behind file.
protected void Page_Load(object sender, EventArgs e)
{
    // If this is a special IsLookup request, then we need to run different
    // code than we usually do.
    if (Request.Headers["IsLookup"] != null)
    {
        // Get the name part of the message sent.
        string nameStr = Request.Form["name"];

        // Just respond with an example string.
        string res = ProcessString(nameStr);
        Response.Write(res);
        Response.End();
        return;
    }
}

Description of the code. The above code checks to see if the IsLookup header is set. That header was set in the submitCallback function in JavaScript. If IsLookup is not null, we received an AJAX request from the page. We are not going to return the page's markup file, but rather a string the AJAX page requested.

3. Example of POST form syntax

Look at submitCallback() again. It does this: it takes the value of the search box, and makes a special string out of it. Right here is the code that builds the POST string.

=== Example JavaScript code ===

// This is the JavaScript code that builds up a proper form
// POST string, that we can use in C# as Request.Form["name"].
var sendStr = "name=" + inputValue;

=== Value sent by JavaScript from the client ===

name=searchterm

=== ASP.NET reads it like this ===

string nameStr = Reqest.Form["name"];

4. JavaScript QueryString example

HTTP GET is a way to request a page based on a query string. Query strings are well-supported by ASP.NET. The syntax is a little different from the post example I showed above. Here is the JavaScript that sent the request we will be receiving in the Page_Load event below.

// JavaScript function to run that will call into the above Page_Load
// event, where we can deal with it in C#.
// This should be called by the HTML in the page on some event, such as onclick.
function submitCallback(inputValue) {
    var lower = inputValue.toLowerCase();

    request = new XMLHttpRequest();
    request.onreadystatechange = readyCallback;

    var loc = "?word=" + encodeURI(lower);
    request.open("GET", loc);

    request.send('');
}

5. QueryString example in ASP.NET

Here is the code that you can put in a code-behind file in ASP.NET that will receive the above GET request from Figure 4, from JavaScript. It is in the Page_Load event, just like everything else.

protected void Page_Load(object sender, EventArgs e)
{
    // Here is an example of an aspx page being loaded with
    // a GET HTTP request. We can use the QueryString
    // collection on the Reqest.
    string wordStr = Request.QueryString["word"];
    if (wordStr != null)
    {
        // The query string "word" is there. Do something with it.
        return;
    }
}

6. Conclusion

Now we have an .aspx page posting to itself, and the Page_Load event in the code-behind can check for AJAX requests, and respond appropriately. This is a fully-functional, hand-made AJAX application. This shows you how to link the world of C# with that of Firefox, Safari, Chrome, and Internet Explorer.

Internet Explorer 6. The JavaScript code here won't work with IE 6.0 without some tweaking. All current versions of browsers support native XMLHttpRequest objects.

Frameworks. Developers usually decide to use an AJAX framework after they feel comfortable with the basics shown in this article. Frameworks such as JQuery now offer more advanced user interface and application effects.

Dot Net Perls
ASP.NET | ASHX Handler Tutorial | Cache Examples and Overview | Global Variables Example | Precompiled Site Options | QueryString Usage
C# | Reflection Field Example | Validate Characters in String | Main Args Examples | Enum String Method
© 2009 Sam Allen. All rights reserved.