I've migrated my blog

Thanks for visiting my blog. I am no longer maintaining this and I've migrated the blog to my personal domain . If you would like to follow my blog kindly use my new RSS feed

Sunday, June 26, 2011

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

This blog post is the continuation of my previous blog post. In that 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.

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 build 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.

Friday, June 24, 2011

ASP.NET MVC 3 Ajax - Part I

In this blog series ASP.NET MVC3 Ajax we are going to explore about implementing Ajax features in ASP.NET MVC3 Web application and this blog post will cover the basics of ASP.NET MVC3 Ajax.

MVC3 makes use of Unobtrusive javascript which results a clear and clean seperation between the functionality and the View/Presention of the webpage. We can introduce Ajax features to the MVC3 application using two ways.
  1. Ajax Helper Methods - Enable us to achieve Ajax without writing no/less javascript
  2. jQuery Ajax - We need to write the code using javascript and jQuery ajax
Ajax Helper Methods are very simple and intutive to get start with. So, I'll be covering the Ajax Helper Methods and will cover the jQuery Ajax in the future posts of this blog series.

Ajax Helper Methods

It enable us to implement ajax feature without writing much code. Ajax.ActionLink() is one of the fundamental Ajax helper method that returns a anchor element (<a></a>) with the URL of the action method; When the action link is clicked, the action method in the specified URL is invoked asynchronously and result is sent back to the client. Let us see it in detail by using sample demo application.
  • Create a new ASP.NET MVC3 Project "AjaxGettingStarted"
  • Select "Empty" template and "Razor" as view engine and click "Ok"
  • ASP.NET MVC3 project template shipped with the scripts folder which contains the all the jQuery library files that are required for doing Ajax and other client side functionalities. To implement ajax we should use the references of "jQuery" and "jQuery.unobtrusive-ajax" minified js files in our view
  •  
  • Create a Controller with the name ""HomeController" by right clicking the "Controllers" folder and select "Add" -> "Controller"
  • The HomeController.cs file will be created under controllers folder with the following code.

    public class HomeController : Controller    
    {
            public ActionResult Index() 
            { 
    
                return View(); 
    
            } 
    
        }
  • Then right click inside the Index() Action Method and select "Add View". Leave the default setting and click "Add".
  • This would create the view "Index.cshtml" under the folder "Views/Home".
  • Add the following action method in HomeController.cs file
    public string GreetMe()
            {
                return "Hello ASP.NET MVC3 Ajax!!";
            }
    
    This action method will be called asychronously called using Ajax.ActionLink helper method. This just written a string which will be displayed in the view via Ajax.
  • Add the script reference to the "jQuery" and "jQuery.unobtrusive-ajax" minified js files in Index.cshtml file.

  • 
    
    
  • Now all the setup in place to implement the basic Ajax functionality using Ajax.ActionLink Helper method. Before seeing this method in action let me explain bit more about this method. There are 12 overloads for this method amoung which the simplest one is Ajax.ActionLink(string linkText, string actionName, AjaxOptions ajaxOptions). The first parameter is the Link text which will be displayed in the view, the second parameter is the name of the action method which should be invoked while clicking the action link and the third parameter is AjaxOptions which defines how the Ajax request/response will take place and used to tell MVC exactly what you want your Ajax call to do.
  • AjaxOptions class will have the following properties.Confirm - Gets or sets the message to display in a confirmation window before a request is submitted.HttpMethod - Gets or sets the HTTP request method ("Get" or "Post").

    InsertionMode - Gets or sets the mode that specifies how to insert the response into the target DOM element.

    LoadingElementId - Gets or sets the id attribute of an HTML element that is displayed while the Ajax function is loading.

    OnBegin - Gets or sets the name of the JavaScript function to call immediately before the page is updated.

    OnComplete - Gets or sets the JavaScript function to call when response data has been instantiated but before the page is updated.

    OnError - Gets or sets the JavaScript function to call if the page update fails.

    OnSuccess - Gets or sets the JavaScript function to call after the page is successfully updated.

    UpdateTargetId - Gets or sets the ID of the DOM element to update by using the response from the server.

    URL - Gets or sets the URL to make the request to.
  • In our sample demo application we are just going to have a link called "Greet Me". Upon clicking on that click we are going make Ajax request to GreetMe action method and populate a div tag with the value returned by the action method
  • Add the following code in the index.cshtml file. which implements the above step.
    @Ajax.ActionLink("Greet Me", "GreetMe", new AjaxOptions() { UpdateTargetId="divGreetings", HttpMethod="GET" })
    This ActionLink method call just creates an Ajax action link with the text "Greet Me", upon clicking the link it invoke the "GreetMe" action method name which we already defined in the HomeController with the ajax option "HttpGetRequest" and update the Dom element with id "divGreetings" with the results that we are getting from the GreetMe action method, which is a simple string "Hello ASP.NET MVC3 Ajax!!"



Summary

In this blog post we have implemented a basic ajax feature using Ajax.ActionLink helper method. In the next blog of the series we would see how to add some add interative animation during the ajax request.