My problem is that the calendar is rendering before the JSON response is sent to the browser. In other words when we get to the array search my array is empty. How would I fix this?
UPDATED: I gave up on trying to request more dates on month change, so now I just get about 6 months worth of events on my first call and display it all at once. Below is the working code.
$(document).ready(function () {
var actionCalDates = [];
//var orgID = 0;
var currentDate = new Date();
dateCount = 0;
getDates(1, currentDate.getMonth(), currentDate.getFullYear());
function displayCalendar() {
$("#calendar").datepicker({
dateFormat: 'dd/mm/yyyy',
beforeShowDay: function (thedate) {
var theday = (thedate.getMonth() + 1) + "/" + thedate.getDate() + "/" + thedate.getFullYear();
//console.log("Before the if my array contains: " + actionCalDates);
if ($.inArray(theday, actionCalDates) == -1) {
//console.log(theday + " Not Found");
return [false, "", ""];
} else {
//console.log(theday + " Found");
return [true, "specialDate", "Actions Today"];
}
}
});
}
function getDates(orgID, month, year) {
dateCount += 1;
if (dateCount < 4) {
$.ajax({
url: "/Calendar/getEvents",
data: {
'orgID': orgID,
'month': month,
'year': year
},
type: "GET",
dataType: "json",
success: function (result) {
//console.log(result);
for (var i in result) {
actionCalDates.push(result[i]);
//console.log("Pushed to the array: " + actionCalDates[i]);
}
//console.log("Array currently holds: " + actionCalDates);
displayCalendar();
}
});
}
}
});
Code Behind C# controller:
public JsonResult getEvents(int orgID, int month, int year)
{
DateTime orgDate = Convert.ToDateTime(month + "/" + orgID + "/" + year);
var fromDate = orgDate;
var toDate = orgDate.AddMonths(7); //last month and the next 6 months
var events = db.Events.Where(e => e.StartDate >= fromDate && e.EndDate <= toDate).ToArray();
var eventlist = from e in events
select new
{
date = e.StartDate.ToString(),
};
List<string> EventDates = new List<string>();
foreach (var currentEvent in eventlist)
{
DateTime dt;
dt = Convert.ToDateTime(currentEvent.date.ToString());
EventDates.Add(dt.Month + "/" + dt.Day + "/" + dt.Year);
}
return Json(EventDates, JsonRequestBehavior.AllowGet);
}