
ASP.NET Webforms Anwendungen und Ajax (Teil 1)
ASP.NET Webforms Anwendungen und Ajax (Teil 1)
It should be clear to everyone that static or dynamic pages that rebuild the entire page with every request are no longer acceptable today. Spoiled by web applications such as Google Maps or Outlook Web Access, end users expect web applications that offer a similar level of user comfort to desktop applications.
As developers of such web applications, this means that we can no longer limit our development activities to the server alone, but must also become active on the client side in order to meet the high expectations of our users.
I would like to answer the question of what “becoming active on the client side” actually means in a short series of articles on my blog.
The client – the unknown entity
Nowadays, there are a number of Ajax frameworks available that aim to take care of the “dirty” work involved in creating dynamic websites. However, since I believe it never hurts to know what these magical tool sets and frameworks are doing under the hood, today we will roll up our sleeves and do the “dirty work” on the client ourselves.
Before we get started, however, we should take a look at the necessary ingredients and briefly clarify what each of them is.
JavaScript
The J in AJAX. A client script language that is unjustly feared and/or ridiculed by many developers ;-) The script code is either embedded directly into a page or stored in an external file. JavaScript is used to manipulate the DOM.
The browser’s Document Object Model (DOM)
The browser’s DOM is an interface that provides access to the underlying (X)HTML document. The DOM allows me to change the appearance and structure of a web page.
- The XMLHttpRequest object
One of the objects of the browser’s window object (at least in modern browsers; otherwise, an ActiveX object). It enables a script to send an (asynchronous) request to a web server.
The interaction between the three components can be summarized as follows:
Let’s get started!
We now know what we need, but we still don’t know how to use the components to integrate AJAX into our own website.
Let’s start with a small and very simple example.
We will create a simple ASPX page consisting of a link and a placeholder area. When the user clicks on the link, this placeholder should be filled with the content of a static file located on the server.
The corresponding HTML code for the ASPX page looks like this:
<form id="form1" runat="server">
<div>
<p>
<a href="#">Click here to request a static file </a>
</p>
</div>
<div id="content">
Please click on the link to fill in this section.
</div>
</form>
The link that will later initiate the Ajax action is defined in lines 5 and 6. The area that will later be replaced is the content of the DIV tag from line 9.
However, the whole thing is not particularly dynamic yet. To achieve this, we need some JavaScript:
<script type="text/javascript">
var xmlHttp;
window.onload = function () {
initializeXmlHttp();
}
function initializeXmlHttp() {
if (window.XMLHttpRequest) {
// IE7, IE8, Mozilla, Safari, Opera
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE 5.x, 6
} catch (e) {
alert('Ajax requests are unfortunately not possible due to the current security settings.');
}
}
}
function sendAjaxRequest(url) {
if (xmlHttp) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = requestFinished;
xmlHttp.send(null);
}
}
function requestFinished() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = xmlHttp.responseText;
}
}
}
</script>
The script first declares a variable in line 2 that holds a reference to the XMLHttpRequest object. As described above, this allows an asynchronous query to be sent to the server.
The initializeXmlHttp function starting at line 7 now fills this object with life. The code should be fairly self-explanatory. Line 8 checks whether the XMLHttpRequest object is attached to the window object. If so, a new XMLHttpRequest object can be created. If this is not the case, it must be created as an ActiveX object.
The function sendAjaxRequest from line 20 submits the actual query. To do this, it first checks in line 21 whether the variable xmlHttp could be initialized. If this is not the case, no query can be sent. Then, in line 22, an asynchronous connection is opened with the open method. This method receives the method (“GET” or “POST”), the URL, and a flag indicating whether the request should be sent asynchronously as parameters.
Line 23 specifies a callback function (in our case, requestFinished) that is to be called as soon as a response to the request has been received.
Line 24 finally sends the request.
The function requestFinished from line 28 processes the response from the web server. Since a request goes through various phases, the function in line 29 uses the readyState property to check whether the request has actually been completed.
Since completion does not always mean “it worked,” the next line checks whether the request was also completed successfully (HTTP status code 200).
The actual processing now takes place in lines 31 and 32. Line 31 retrieves a reference to the area to be replaced (our div with the ID Content). Line 32 finally overwrites this content with the server’s response.
For this to work, the sendAjaxRequest function from line 20 must still be called from our HTML code. To do this, we simply extend our link from lines 5/6 with the onclick attribute.
<a href="#" onclick="sendAjaxRequest('static.html');">Click here to request a static file </a>
Ausgeführt sieht das ganze dann wie folgt aus:
Very nice …
So now we know how to reload static files, but doesn’t the X in AJAX stand for XML web services?
Exactly! That’s why I added a small web service with two meaningless methods to the demo project:
public class AjaxDemoService: System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string Echo(int number)
{
return string.Format("You entered {0}.", number);
}
}
But how do we call up such a service using JavaScript?
The answer can be found relatively quickly by entering the URL of the web service in the browser. The page that appears lists all the methods of the web service. Clicking on one of these methods reveals how the method must be called. In the example of the HelloWorld method, the output for an HTTP Post request looks like this:
The following output is produced for the Echo method:
Compared to our previous approach to dynamically reloading the static file, it is noticeable that the method used to initiate the request can no longer be GET, but must now be POST.
In addition, a specific content type, namely application/x-www-form-urlencoded, is now required. With the Echo method in particular, it is noticeable that data must now also be sent to the server.
To cover the changed requirements, I am extending the existing JavaScript with a new function:
function postAjaxRequest(url, data) {
if (xmlHttp) {
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = requestFinished;
xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlHttp.send(data);
}
}
The new function, postAjaxRequest, is similar to the previous function sendAjaxRequest. The changed requirements were relatively easy to integrate. In line 3, a GET was changed to a POST. In line 5, the additionally required content type is set. In line 6, the method send is no longer passed a fixed null as a data parameter. Instead, the new argument data is passed on.
The HTML code also only had to be expanded slightly. It receives two new links to call the two web methods:
<a href="#" onclick="postAjaxRequest('AjaxDemoService.asmx/HelloWorld', null);">
Hier für Hello World WebService klicken
</a>
<br />
<a href="#" onclick="postAjaxRequest('AjaxDemoService.asmx/Echo', 'number=1');">
Hier für Echo WebService klicken
</a>
The result then looks as follows:
Conclusion
Integrating Ajax into a web application is not particularly difficult from a technical point of view. This blog post has shown that even without “magical” frameworks, Ajax functionalities can be integrated with just a few lines of JavaScript. Of course, the implementation shown is very rudimentary. For example, the XML returned by the web service has not yet been parsed, and there is virtually no error handling. However, integrating this into the example would have gone beyond the scope of a blog post. For these very reasons, there are already ready-made frameworks such as ASP.NET AJAX or jQuery that take care of this detailed work for you.
Before using such a framework, however, you should know the basics of what happens behind the scenes. And it is precisely these basics that we have covered in this blog post.
Incidentally, I will make the complete example available for download over the weekend.
Other posts

Lebensdauer von SQLite-Datenbankverbindungen in .NET MAUI und Xamarin.Forms: Kurz- oder Langlebig?

Verstärkung bei der Quality Bytes GmbH in Sinzig gesucht (Softwareentwickler .NET, Softwareentwickler Angular, Xamarin, ASP.NET Core)

Klickbare Labels Mit Xamarin.Forms

Fehler: Xamarin.Forms legt in Visual Studio 2017 Update 5 leere Projektmappe an

Was tun, wenn die Xamarin App während der iOS Store Prüfung wegen einer Exception abgelehnt wird?

Hilfe! Xamarin iOS Simulator startet nicht und stürzt mit Fehler: 'A fatal error occured when trying to start the server' ab