1
votes

I am using the fullCalendar library in Visual Studio 2015. I am having trouble populating events from an AJAX command. No events are populating on the calendar. If I pass only one datetime and set allDay = true, it will populate the event. I need it to work with time as well and ave multiple events per day.

JS Code:

$(document).ready(function () {

$(".calendar").fullCalendar
    ({
        header: {
            left: 'month,basicWeek,basicDay,today',
            center: 'title',
            right: 'prev,next'
        },
        weekends: false,
        eventLimit: true,
        theme: true,
        editable: false,
        fixedWeekCount: false,
        events: function(start, end, timezone, callback)
        {$.ajax
            ({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Calendar/GetCalendarEvents",
                dataType: 'json',
                success: function (data)
                {

                    var events = [];
                    $.each(data, function (index, value) {

                        events.push({
                            id: value['id'],
                            title: value['title'],
                            date: value['date']
                            //all data
                        });
                        console.log(value)
                    });
                    callback(events);
                },
                error: function (xhr, err) {
                    alert("ERROR! - readyState: " + xhr.readyState + "<br/>status: " + xhr.status + "<br/>responseText: " + xhr.responseText);
                }
            });

        }   });})

Note: The above code was one of may attempts to get it working. I have tried coding it differently before.

Controller Code:

public ActionResult GetCalendarEvents()
    {
        var events = new List<VMCalendarEvents>();
        var db_events = db.PatientVisits.ToList();
        foreach(var e in db_events)
        {
            DateTime visit_start = Convert.ToDateTime(e.VisitStart);
            DateTime visit_end = Convert.ToDateTime(e.VisitEnd);

            var calEvent = new VMCalendarEvents
            {
                id = e.PatientVisitID.ToString(),
                title = "Placeholder Title" + e.PatientVisitID.ToString(),
                date = visit_start.ToShortDateString(),
                start = visit_start.ToString(),
                end = visit_end.ToString(),
                editable = true,
                allDay = false

            };
            events.Add(calEvent);
        }

        var rows = events.ToArray();
        return Json(rows, JsonRequestBehavior.AllowGet);}

Controller Code Output

JS Objects from Controller

EDIT: Problem Solved

So after some investigating I decided to use Razor in MVC to solve the problem. Instead of writing it into a seperate JS file, I put it into a header in the html file. By implementing the code below I was able to get the objects in the date formats of (yyyy-MM-ddTHH:dd & MM/dd/yyyy hh:mm tt):

    $(function () {

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultDate: '2017-06-12',
        editable: true,
        events: '@Url.Action("GetCalendarEvents", "Calendar")',

    });

});

I called the Controller using the URL Action command and return the JSON data as a ActionResult.

1
what's the point of your ` $.each` loop? Looks to me like the data from the controller is already in the correct format, no need to translate it. You could just do callback(data) without any of the in-between steps. Also, your controller should be accepting the "start" and "end" parameters and only returning the data for the currently displayed dates, otherwise every time the user goes to a new date or view in the calendar, it will download all your events again and again, which is very inefficient. - ADyson
in terms of the date, you would be wiser to output the dates in ISO format, to avoid any problems with ambiguous formats or internationalisation. Currently it looks like they're in maybe an american M/D/Y format, but in that case fullCalendar won't know whether "05/03/2017" is 3rd May or 5th March. YYYY-MM-DD is unambiguous. It could be that the calendar is either interpreting some dates incorrectly, or even failing because it doesn't understand them - have you checked your browser console for errors or warnings when you're loading the events? - ADyson

1 Answers

2
votes

Fullcalendar might not like your slashes '/' in your date fields. Try hyphens '-' instead. The documentation (https://fullcalendar.io/docs/utilities/Moment/) is more detailed about what formats for date/time work.

For reference, here is my fullcalendar code using JSON from AJAX (note that my events do not have an end time, but this was by choice):

{
    $.ajax({
        url: 'example.json',
        dataType: 'json',
        success: function(doc) {
            var events = [];
            $.each(doc, function(index, element) {
                events.push({
                    title: element.title,
                    start: element.time,
        url: element.url,

                });
            });
            callback(events);
        }
    }) //ajax
    }

And the JSON file (example.json):

    [
{"time": "2017-06-06 09:00:00", "title": "Get It Done in June ", "url": "http://example.org"},
{"time": "2017-06-07 14:00:00", "title": "Fighting Imposter Syndrome for Dissertating Students ", "url": "http://example.com"},
{"time": "2017-06-14 14:00:00", "title": "Entering into the Academic Conversation", "url": "http://example.biz"}
]