Use ASP.NET code-behind (Page_Load event) with AJAX in a working program. We require a way to implement AJAX and have it work with code-behind. We want the browser to send messages to the server, and have our ASP.NET code respond to them. Fortunately, there is an effective way to do this with 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--it returns the whole page's starting markup file, but also responds with any data it wants to an XMLHttpRequest send call.
| When the user does this | Then this method in ASP.NET runs |
| Requests a URL in the browser | Page_Load |
| Posts a request to the page in JavaScript on the page | Page_Load |
The examples I show next use the HTTP POST action, but you may want to use GET, which I show later in this post. Make a custom function that is activated by the user clicking or whatever. Let me show the JavaScript, which you can put in the script block. This is the JavaScript AJAX code we put in the HTML.
<script type="text/javascript">
var request;
// 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();
// 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 that 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". What this is used for is telling the aspx .cs file that this is a special IsLookup request.
Now, let's look into Page_Load in the code-behind file of this page. This code is in C#, which you are probably familiar with. This code in Page_Load is always executed, even in POST requests. After the code I try to explain it more.
// 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 a silly, example string.
string res = ProcessString(nameStr);
Response.Write(res);
Response.End();
return;
}
}
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 itself.
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. After I show the JavaScript, I will show some of the corresponding C# code for the query.
// 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;
| This value is sent by JavaScript | ASP.NET reads it like this |
| name=searchterm | string nameStr = Reqest.Form["name"]; |
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. First, let's look at 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('');
}
The above code is in JavaScript and would be in your .js files or in the script tags in HTML. Next I show the code that you can put in a code-behind file in ASP.NET that will receive the above GET request 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;
}
}
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. It doesn't do much, but it shows you how to link the world of .NET C# with the world of Mozilla, Safari, Internet Explorer--the world of JavaScript and XMLHttpRequest.
The JavaScript code here won't work with IE 6.0 without some tweaking. All current versions of browsers support native XMLHttpRequest objects. The big gotcha is Internet Explorer 6.0, which doesn't and requires ActiveX. Look for information about IE 6.0 ActiveX XMLHttpRequest objects for more details.