TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ASP.NET Page_Load Event and AJAX

This ASP.NET article shows how to use JavaScript, AJAX and C# code-behind together.

Page_Load. The Page_Load event handler works with AJAX.

We use ASP.NET code-behind with the C# language. We implement AJAX with JavaScript. The browser sends messages to the server—and the ASP.NET code-behind responds.

AJAX. First, 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.

And: The file can return return the starting markup file, or any data it wants to in response to an XMLHttpRequest.

HTML page with AJAX code

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

// A
// 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>

We 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. In part A, submitCallback takes the value of SearchInput. The input is simply a regular HTML element with an ID in the page. It has a real HTML ID and not an ASP.NET server ID.

Remove ID

Note: SubmitCallback builds a special string for the server that contains "name=" at the front.

In part B, it uses XMLHttpRequest. SubmitCallback sets up the XMLHttpRequest. The XMLHttpRequest uses a POST to the current page, Default.aspx. XMLHttpRequest content type is set to a standard format. The request is posted.

Header: A special header is sent with the POST request to the Default.aspx page. This header can be called anything—I use "IsLookup".

And: The value can be set to something like "true". This tells the aspx .cs file that this is a special IsLookup request.

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

Page_Load method implementation: C#

// 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;
    }
}

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.

And: We are not going to return the page's markup file, but rather a string the AJAX page requested.

POST form. Please 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"];

Query strings. HTTP GET is a way to request a page based on a query string. Query strings are supported by ASP.NET. The syntax is a little different from post. Here is the JavaScript that sent the request we receive in the Page_Load event below.

JavaScript code that implements GET

// 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('');
}

Code-behind. We put this code in a code-behind file in ASP.NET that will receive the above GET request from the JavaScript code. It is in the Page_Load event, just like everything else.

Page_Load method that accesses query string: C#

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;
    }
}

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

Warning: The JavaScript code here fails on old browsers. All current versions of browsers support native XMLHttpRequest objects.

Summary. We looked at using the ASP.NET server-side C# code with JavaScript on the client in an AJAX project. 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.

Review: This shows you how to link the world of C# with that of Firefox, Safari, Chrome and Internet Explorer.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf