ASP.NET MVC3 Ajax Part II - Adding Animation to Action Link

This blog post is the continuation of my previous blog post. In the last blog post we have seen how to achieve the basic Ajax functionality using Ajax.ActionLink() helper method. Probably in many websites you might have seen whenever any ajax request is raised by the user, there would be an associated loading text or a loading gif will be displayed which inform the user that something is going on the background. We are now going to see how to achieve the same using the ActionLink() method.

ActionLink() method uses a declarative approach to do this. All we need to do is to create a div element contains the element which will be displayed during the Ajax request and associate the div element to the ActionLink() method by assigning the ”LoadingElementId” AjaxOption to the div element’s id. Let us see how to do this by using the MVC3 app that we have seen in the previous blog post.

Adding Loading Div Element

Open “Index.cshtml” and append the following div. It just contains image element which will be displayed during ajax request.

Note the inline style. The display has been set to none as it not intended to display only during Ajax request.

Associate Div Element with ActionLink() method

This is very simple. We just need to add the AjaxOption ”LoadingElementId” and assign it to the loading div element’s id. The modified ActionLink() method will look as follows.


Simulating a delay in Action Method

Now when we run the application we might not get a chance to see the loading gif as everything takes place is very less time. In order to see the loading gif, we need to increase the processing time taken by the GreetMe action method. The modified GreetMe action method in HomeController.cs will look as follows. The delay has been introduced by using the Thread.Sleep() method which delay the process by 2 seconds.


Now when we run the application we will be able to see the loading gif when the Greet Me link is clicked.

Summary

In the Part i & ii of this series we have seen a basic Ajax functionality using Ajax.ActionLink() method. The source code of the demo application can be downloaded from here.

Comments