Pages

Wednesday, September 12, 2012

Using jQuery FullCalendar and C# .NET (JSON)

Create a web service that will supply the data to the jQuery FullCalendar

On the web service, create a 'calendar' object
public class CalendarEvent
{
  public string Id;
  public string Title;
  public string StartDate;
  public string EndDate;
}

Create the web service method that will supply the data
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
[WebMethod(Description = "Return Calendar Events")]
public List GetCalendarEvents()
{
  List calendarEvents = new List();
  
  // get data from the database
  businessclass biz = new businessclass();  
  SqlDataReader sqlReaderCalendarEvents = biz.ReturnAllActivities();

  if (sqlReaderCalendarEvents.HasRows)
  {
    while (sqlReaderCalendarEvents.Read())
    {
      CalendarEvent calendarEventDetails= new CalendarEvent();
      
      calendarEventDetails.Id = sqlReaderCalendarEvents.GetInt32(sqlReaderCalendarEvents.GetOrdinal("RequestID")).ToString();
      calendarEventDetails.Title = Server.HtmlDecode(sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("Title")));
              
      calendarEventDetails.StartDate = sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("ActivityStartDate"));
      calendarEventDetails.EndDate = sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("ActivityEndDate"));
      // add the 'calendar' object to the list of 'CalendarEvent' object
      calendarEvents.Add(calendarEventDetails);
    }
  }

  sqlReaderCalendarEvents.Close();

  // return the list of 'CalendarEvent' object
  return calendarEvents;
}

On your fullcalendar object, call the web service
$('#calendar').fullCalendar({
  events: function(start, end, callback) {
    $.ajax({
      type: "GET",                        
      url: "WebService.asmx/GetCalendarEvents",
      dataType: 'json', // datatype returned by the webservice
      contentType: "application/json; charset=utf-8",
      data: {
        // requires UNIX timestamps
        start: Math.round(start.getTime() / 1000),
        end: Math.round(end.getTime() / 1000)
      },                        
      success: function(doc) {
        var events = [];

        // loop through each event and make an array of events
        $.each(doc.d, function(index, calendarEventItem) {                    
          events.push({
            title: calendarEventItem.Title,
            start: calendarEventItem.StartDate,
            end: calendarEventItem.EndDate,
            className: calendarEventItem.CssClass,
            url: calendarEventItem.URL
          });
        });

        callback(events);
      }
    });
  }
});