Friday, February 5, 2010

Implementing jQuery FullCalendar PlugIn with ASP.NET MVC

I have been using jQuery for most of my javascript work, so when I need to display a calendar related data in a "month view", I did a search for jQuery plug-ins that will work with my existing project (and extensible to be used for future projects as well). My current projects are built using ASP.NET MVC, so working with jQuery and its plug-ins just makes sense.

After a careful research, trial & error, I finally picked "FullCalendar" jQuery plug-in. You can download it here. It says in its website as:

"FullCalendar is a jQuery plugin that provides a full-sized, drag & drop calendar like the one below. It uses AJAX to fetch events on-the-fly for each month and is easily configured to use your own feed format (an extension is provided for Google Calendar). It is visually customizable and exposes hooks for user-triggered events (like clicking or dragging an event)"

So first thing first, let's just try to get the calendar to display. In one of my view, let's call it "MonthView.aspx", I have this javascript (jQuery):
 $(document).ready(function() {
   $('#calendar').fullCalendar();
}
Somewhere in the HTML:
 <div id='calendar'></div>
Set the controller code to display the view:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult MonthView() {
   return View();
}
At this point, we should be able to display the empty calendar by going to http://<site>/<controller_name>/MonthView.

So now, we are going to modify this empty calendar to display the data from somewhere (db/xml/etc) via AJAX. For this, I created a class called "CalendarEvent" which structure is mimicking the JSON object model described in here; such as this:
 public class CalendarEvent {
   public string id { get; set; }
   public string title { get; set; }
   public string date { get; set; }
   public string start { get; set; }
   public string end { get; set; }
   public string url { get; set; }
}
Then in the controller code:
 
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CalendarData() {
   DateTime start = new DateTime(1970, 1, 1);
   DateTime end = new DateTime(1970, 1, 1);

   start = start.AddSeconds(double.Parse(Request["start"]));
   end = end.AddSeconds(double.Parse(Request["end"]));

   // call middle tier/orm/whatever to get data from source
   List list = SearchForEvents(start, end);
   
   return Json(list);
}

private List SearchForEvents(DateTime start, DateTime end) {
   // code to get data here

}
Now, we need to modify the jQuery to call the action in our controller to return data:
 
$(document).ready(function() {
   $('#calendar').fullCalendar({
      events: '<%= Url.Action("CalendarData", "MyController") %>'
   });
}
Voila!

No comments: