Using JQuery to perform Ajax calls in ASP.NET MVC

As I was looking around for ways to enable Ajax in the current ASP.NET MVC release I found a couple of things that I found pretty useful and thought I should share.

The J in Ajax (JQuery)

The muscle behind the actual asynchronous calls comes from JavaScript. I looked around at a bunch of existing JavaScript libraries and settled on JQuery because of the way it leverages existing CSS knowledge. The three things that the library should do easily are:

  1. Help me easily display an "updater" to let user know something is happening (i.e. loading data),
  2. Assist in making the actual Ajax call without any hassle,
  3. and, most importantly, let me get 1 and 2 working without headaches.

Here is how JQuery helps in the three cases:

  1. The "updater":
    $('#updater').show();
    $('#updater').hide();
    Notice the way JQuery uses the standard CSS id selector. Could it be any easier?
  2. JQuery has the following Ajax calls available in its library:
    object.load( )
    $.get( )
    $.post( )
    $.getJSON( )
    This takes away (hides) all of the XmlHttp object nonsense from the whole Ajax call.
  3. See 1 and 2

ASP.NET MVC

There are tons of good posts/tutorials on exactly how the ASP.NET MVC model works so I will not attempt to get into it too much here. The most important thing to know is that there are three things working together:

  1. The Controller,
  2. The Model, and
  3. The View

The controller handles all of the requests, asks the model for data, and then instructs the view to present the data (if any) returned.

Routes

One of the neat things about the MVC framework is the notion of routes. The default route setup is as follows:

routes.MapRoute(   
	// Route name
	"Default",
	// URL with parameters
	"{controller}/{action}/{id}",  
	// Parameter defaults                            
	new { controller = "Home", action = "Index", id = "" }     
);

This simply means that, from the root of your web app, whenever a URL of the form http://root/foo/baz/bar is presented, the routing engine will call the foo controller with the baz action while supplying it with the bar id.

Some Code

Enough explanation, now to some code!

The Model

Since this is not an exercise in using the database, I created a simple Model class for students:

public class Student   
{   
   public string FirstName { get; set; }   
   public string LastName { get; set; }   
   public int StudentId { get; set; }   
           
   public static IQueryable<Student> GetStudentDataList()   
   {   
      return new List&lt;student&gt;()   
      {  
         new Student { FirstName = "John", LastName = "Smith", StudentId = 1},  
         new Student { FirstName = "Susan", LastName = "Connor", StudentId = 2},  
         new Student { FirstName = "Bryan", LastName = "Jones", StudentId = 3},  
         new Student { FirstName = "Lucy", LastName = "Vargas", StudentId = 4},  
         new Student { FirstName = "Robert", LastName = "Jimenez", StudentId = 5},  
         new Student { FirstName = "Seth", LastName = "Juarez", StudentId = 6},  
         new Student { FirstName = "David", LastName = "Meeks", StudentId = 7},  
         new Student { FirstName = "Olivia", LastName = "Rassmusen", StudentId = 8},  
         new Student { FirstName = "Viola", LastName = "Masterson", StudentId = 9},  
         new Student { FirstName = "Russel", LastName = "Jones", StudentId = 10}  
      }  
      .AsQueryable<Student>();  
   }  
}

This simply creates a new list of Students and returns them as an IQueryable.

The Controller

Since I want to only pass JSON serialized objects over the wire when making the Ajax calls, there is a handy return type for the action in the controller called JsonResult:

public JsonResult Find(string name)   
{   
   // To simulate &quot;wait&quot;   
   System.Threading.Thread.Sleep(1500);   
           
   return new JsonResult   
   {   
      Data = (from student in Student.GetStudentDataList()   
              where student.LastName.StartsWith(name)  
              select student).ToArray<student>()  
   };  
}

This will serialize the data out in the JSON format. Now for the actual interesting part:

The View

The html for this example is VERY simple:

<div id="query">   
     <%= Html.TextBox("textSearch") %>  <a href="#" id="linkFind">Find</a>    <span class="update" id="updater">   
           <img src="<%= AppHelper.ImageUrl("indicator.gif") %>" alt="Loading" />  Loading...    </span>   
</div>   
<div class="label">Students:</div>   
<div id="studentList"></div>

There is a search box, a link, and update panel, and a div (studentList) that will be populated by the Ajax call. This is where the magic of the routing engine coupled with the JQuery Ajax call comes together:

 $(document).ready(   
     function()   
     {   
        // Hide update box   
        $('#updater').hide();   
                     
        var retrieveData = function(path,  query,  funStart,  funEnd, funHandleData)   
        {   
           // for displaying updater  
           funStart();  
                            
           // retrieve JSON result  
           $.getJSON(  
              path,  
              { name : query },  
              function(data)  
              {  
                 // handle incoming data  
                 funHandleData(data);  
                 // for hiding updater  
                 funEnd();  
              }  
           );  
        };  
                    
        // adding handling to find link  
        $('#linkFind').click(  
           function(event)  
           {  
              event.preventDefault();  
              retrieveData(  
                 // mvc route to JSON request  
                 '/Student/Find/',   
                 // query from textbox  
                 $('#textSearch')[0].value,   
                 // function to show updater  
                 function() { $('#updater').show(); },   
                 // function to hide updater  
                 function() { $('#updater').hide(); },  
                 // retrieving the data  
                 function(data)  
                 {  
                    // clear students (if any)  
                    $('#studentList > div').remove();  
                    // add students  
                    for(s in data)  
                    {  
                       var student = data[s];  
                       $('#studentList').append('<div>(' +  student.StudentId ... you get the idea                   
                     }  
                 }  
              );  
            }  
         );  
      }  
  );

The retrieveData function uses the JQuery $.getJSON call to retrieve the data. It takes as arguments the path to the controller (remembering routes), the argument (in this case the query) that the controller action expects, as well as a couple of functions. These functions will handle the cases where the  request is started, the request is ended, and what to do with the data that is returned. Subsequently we add the event handler to the link that initiates the find request. Notice that we are passing in '/Student/Find/' as the path since we are using the Find action on the StudentController. The argument is passed in from the search text box. This sets into motion the asynchronous request to the controller. The controller then returns a JSON serialized array of Student objects. Once the data is received, the studentList div is then cleared and repopulated.

Screenshot

The request:

request

The response:

response

Conclusion

Hopefully this has been helpful! It was fun putting everything together. Feel free to send me an email or leave a comment on this post if there are any suggestions/comments.

Your email address will not be published. Required fields are marked *

*