AJAX and LINQ are two of the main focuses of Microsoft right now; and no wonder – both have huge potential and power behind them.

In this example, we will show how we can use AJAX coupled with LINQ and XML to create a Web Application that we can use to view stored data instantaneously, as well as add to it in the same way. AJAX provides the ease of use, by making the application run smoothly and efficiently, as if it was a desktop application, while LINQ provides the means to communicate and interact with the XML file and data stored within.

The first thing we need to do is create our XML file. For this example, we will be using something like this:

We will create a form to both read and write to the XML file: We will need three textboxes and a button for additions, and then a button and a textbox for reading. We will construct a form similar to this:

Notice that our buttons have the OnClick handlers pointing to a method. We will get to those in a minute, but first, let’s finish off our ASPX page. The only thing left to do is enable AJAX on this page. We do this by adding a ScriptManager and an UpdatePanel, like so:

Before we start coding, we should make sure we have the correct namespaces. We will be making use of LINQ to XML, so we need System.Xml.Linq.
Our directives will look something like this:

Now back to the buttons. We already added our handlers to the buttons, so we’re now done with the ASPX page and now we can code our methods. We will create a method for the reading of the XML file, as we are likely to use this more than once (other than just on the button click – you’ll see why). Our method will look something like this:

This method makes use of LINQ to first connect with the XML file and then make a selection of all the data within. Once selected, we loop each ‘record’ and output to the textbox control.
We call this method from the button click event:

Next up is adding to the XML file. This actually requires less code than reading. We will code this directly into the button click event. It will look something like this:

We use a try, catch to reduce the number of errors in processing. Again, we are using LINQ to add data to the XML file – first we load the file, and then we simply add a new element into the parent element, referring back to our XML structure will be useful for understanding.
The entire code-behind will look something like this:

Download Source Files