Ajax has been an important part of the web development. Nowadays, most of the websites utilizes the power of Ajax. In this article we will focus on how to use Ajax with the ASP.NET MVC Framework.

Getting Started with Ajax in ASP.NET MVC:

Before diving into the implementation details first add references to the following script files. These script files are already added to your Content folder. Simply refer them in your master pages.



Let's start with the basics. We are going to create a view which shows the current date and time when a link is clicked. The date and time will be fetched using an Ajax call.

The controller's action is implemented below:



The view consist of the following implementation:



The first parameter is the text that should appear in the place of link. The second parameter "GetDateTime" is the name of the action to be invoked on the controller. The AjaxOptions parameter enables the developer to setup parameters related to Ajax requests.

The HttpMethod parameter indicates what Http method is used which in this case is "GET". The UpdateTargetId represents the HTML element ID which will be injected with the response.

You can also find out if your request is an Ajax request or a normal request. This can be performed by using the following code:



You can even cache your Ajax request by decorating it with the OutputCache attribute as shown below:



The screenshot below shows that the request is not modified. We have experienced that this behaves differently in different browsers. Which means some browsers are not able to fetch the response from the browser cache.



Deleting Individual Records Using ASP.NET MVC Ajax:

In this section we are going to implement a scenario where you can delete individual items from your list using asyncronous calls.
 
The first task is to create a class that represent our item. We will be taking the simple class of Stock for our demo. The class is defined as follows:


 
Nothing complicated right!

Now, we need a service that return us with some dummy stock values. We will use a static variable to hold the values in the memory but in real world scenarios you can use any data storage mechanism you like.



In the above code we just added some dummy values to our _stocks static variable. In the next section we will demonstrate how you can display the stocks on your view. 

Displaying Stocks on your View Page:

So, you got dummy stocks loaded up and want a view page to display them. The StockController is responsible for triggering the methods on the StockService. The List action is defined below:



The stocks are displayed on the page using the following code:



The following screenshot shows the stocks display in the table.



Currently, if you click on the submit button nothing will happen. This is because we have not yet implemented any functionality to delete the record.

Deleting Records Asynchronously:

The next task is to implement the functionality to delete individual records. We need some way to submit the form and pass in the stock name which needs to be deleted.

The following code introduces a hidden field which will be responsible for submitting the stock name to the controller's "DeleteItem" action.



We have named our hidden field "name" since our action "DeleteItem" takes a parameter called "name".



Next, we need to define a form element which will invoke the "DeleteItem" action. If you define a single form element and nest the complete table inside that form then on submission all the hidden fields are sent to the server. This will produce incorrect results since you are only interested in sending the single parameter on which the delete was triggered.

For this to work property you must enclose each submit button and the hidden field in its own form tag as shown below:



Now, if you click the submit button you will notice that only the appropriate value is sent to the server. Also, notice that we are using Ajax.BeginForm and not Html.BeginForm. Ajax.BeginForm makes sure that the request is submitted using the XmlHttp by adding XmlHttp headers to the request.

Removing Deleted Item from the DOM:

Although you have managed to invoke the controller's "DeleteItem" action and removed the item from the stocks collection but it is still not reflected on the interface. It is developer's responsibility to remove the deleted item from the DOM tree.

The "DeleteItem" action returns back a JavaScriptResult which is executed on the client side.



A word of advice is not to use the above method. It is never a good idea to return JavaScript from your server side method which will be executed on the client. This open security holes and any malacious script can be executed easily. Also, this becomes a hard to maintain solution since you are concatenating the strings together to create a JavaScript script.

The onItemDeleted is a function on the client side which will remove the item from the table.



What about Action Links?

The submit buttons might do the work but they also look ugly and most probably your client will not approve grey dull looking buttons. You might be wondering that why can't you just use links instead of submit buttons. Unfortunatly, HTML links are not easy to use when submitting the form. But there is a way to use JQuery to perform an asyncronous request and get the work done.

Using Action Links with JQuery:

If you are not familiar with JQuery Ajax API then it is recommended that you check out the following article:

A Look into JQuery Ajax API

The implementation is shown below:



The first parameter represents the text to be displayed for the link which in this case is "Delete". The next parameter represents the action which will be triggered when the link is clicked. The third parameter indicates the route values to be passed to the action method. We are passing the name of the stock to the "DeleteItem" action on the controller. The last parameter simply sets some additional attributes on the ActionLink.

If you use the above code then it will simply submit the form without performing asyncronous request. In order to make our link behave asyncronously we have to attach the onclick event of the link to invoke the action with XmlHttp request.



The above code invokes the url of the link which will be a controller's action using the $.get function of JQuery. The $.get function will perform the GET request asynchronously. When the response is returned the OnItemDeleted function is invoked which simply removes the element from the table.



The animation is shown below:




Wait! there is something wrong with the animation. The LoadingElement is not displayed at all. But not to worry as we can easily fix the issue and show a loading message when the record is being deleted.

Creating a Loading Message While the Record is Deleted:

There are couple of methods to show the loading DIV. The easiest one will be to add an element "divLoading" in the master page and simply show the element while the link is clicked and hide it when the request is completed.

In our implementation we have dynamically injected the div into our page. Please note that this might not be the best method but we just wanted to show that this is one of the possible  solution.



We have declared all the style in our code but you can always create a custom style for your loading DIV and place it in the CSS file.

The result is shown below in the animation:




Conclusion:

In this article we demonstrated how to perform Ajax request when using ASP.NET MVC Framework. We also showed how to use ActionLink to create asyncronous request instead of using submit buttons. 

[Download Sample]