Using JQuery FullCalendar with ASP.NET MVC and Entity Framework

I had a need to use a calendar component in my application. Calendars are hard to come by, that also act as a scheduling component. In comes JQuery FullCalendar, a plugin that renders a calendar with event components.

To set this up

1. Create an Entity Framework model with all of the AdventureWorks entities.  Choose whatever template you like. Leave the context name as the default “AdventureWorksEntities”.

2. Create a new MVC project. Add a new controller named OrderHistoryController. The OrderHistoryController that I used is defined as the following:

public class OrderHistoryController : Controller
{
//
// GET: /OrderHistory/
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult List(long start, long end)
{
var epoch = new DateTime(1970, 1, 1);
var startDate = epoch.AddMilliseconds(start);
var endDate = epoch.AddMilliseconds(end);

var ctx = new AdventureWorksEntities();
var data = ctx.SalesOrderHeaders
.Where(i => startDate <= i.OrderDate && i.OrderDate <= endDate)
.GroupBy(i => i.OrderDate)
.Select(i => new { OrderDate = i.Key, Sales = i.FirstOrDefault()}).Take(20).ToList();

return Json(data.Select(i => new
{
title = (i.Sales.Customer != null) ? i.Sales.Customer.AccountNumber : “Untitled”,
start = i.OrderDate.ToShortDateString(),
allDay = true
}));
}

}

The Index action serves up the view.  Once the view is loaded, an AJAX request is made back to the server, looking for any orders.  Using LINQ, we load up some of those records.  I used a GroupBy statement so that I could get one record back per date for a given month, as a way to test with a single record per day.

JSON is the preferred mechanism to return to the client.  We’ll need to massage the data a little bit in order to work with the full calendar.   For instance, we’ll have to convert the date appropriately.  For simplicity, I used ToShortDateString to get the date and parse it in JavaScript.  However, it would have been more appropriate to convert the date to Epoch time (time since 1/1/197o).

3.  Download JQuery FullCalendar from the following URL: http://arshaw.com/fullcalendar/download/.  Copy the JS and CSS files to your project, in the Content and Scripts folder (or whatever folder structure you are using).  The files includes are:

  • fullcalendar.css – the core CSS file
  • fullcalendar.print.css – the CSS stylesheet for printing a calendar
  • fullcalendar.js – the core JS file
  • fullcalendar.min.js – the minified JS file
  • gcal.js – Google calendar integration

4.  Add scripts to your page

Rather than adding all the scripts to every page, I added the scripts to the OrderHistory view.  To do this, I started by creating a bundle.  Open up Bundle.config and add the following:

bundles.Add(new ScriptBundle(“~/bundles/calendar”).Include(

#if DEBUG

“~/Scripts/fullcalendar.js”

#else

“~/Scripts/fullcalendar.min.js”

#endif

));bundles.Add(new StyleBundle(“~/Content/calendar”).Include(

“~/Content/fullcalendar.css”,

“~/Content/fullcalendar.print.css”

));

We use these bundles within the view. To setup the calendar, all that we need to do is add a DIV to a page with an ID, like <div id=”container”></div>. The FullCalendar plugin simply attaches to

$(“#calendar”).fullCalendar({
    header: {
        left: ‘prev,next today’,
        center: ‘title’,
        right: ‘month,agendaWeek,agendaDay’
    },
    editable: true,
    eventClick: function(i, evt, view) {
               
    },
    events: function (start, end, callback) {
        $.ajax({
            type: “post”,
            url: ‘@Url.Action(“List”, “OrderHistory”)?start=’ + start.getTime().toString() + “&end=” + end.getTime().toString(),
            success: function (d) {
                var list = [];
                for (var i = 0, len = d.length; i < len; i++) {
                    var item = d[i];
                    item.start = new Date(item.start);

                    list.push(item);
                }

                callback(list);
            },
            error: function (e) {
                debugger;
            }
        });
    }

});

The plugin supports a variety of members defined in the documentation that can be specified at initialization time. The key is the events property, which defines the source of the events. The source can be a static list, a pointer to a page or web service, or even a function callback. The latter option gives you the most flexibility, and I’ve demonstrated it’s usage in this example. The callback gets a start and end parameter. These parameters are dates, converted to epoch time (in milliseconds) as they are sent to the server. JQuery is used to make the call to the server, and as the results come back, the process does some massaging first. For instance, a date is coming back to the client in string form, and converts the date back to a date form.

Once our final list is complete, and to load them into the calendar, they are passed to the callback. The plugin handles all of the loading of data into the calendar. Remember from the MVC controller, it returned a title, start (date), and an allDay indicator. Using this data is what the FullCalendar plugin uses as the data source. More parameters

8 thoughts on “Using JQuery FullCalendar with ASP.NET MVC and Entity Framework

  1. Be aware that this won’t necessarily work if you (or your server) have a different culture. In the UK ToShortDateString() will return dd/mm/yyyy, which won’t be parsed correctly by the ajax success callback.

    Use OrderDate.ToString(“yyyy-MM-dd”) to ensure it will be parsed correctly.

    Like

Leave a comment