1
votes

I'm creating the fulcalendar in document ready and I have an asp button that runs the following C# function to fetch the data.

 public void getAppointments()
    {
        List<Appoinment> appoinmentList = new List<Appoinment>();
        AppointmentController appointmentController = new AppointmentController();
        PublicUserProfileController publicUserProfileController = new PublicUserProfileController();
        PublicUserProfile publicUserProfile = new PublicUserProfile();
        //appoinmentList = appointmentController.fetchAppointmentByConsultent(Int32.Parse(Session["ICid"].ToString()));
        appoinmentList = appointmentController.fetchAppointmentByConsultent(3);

        var frontAppoinmentList = new List<object>();

        foreach (var appoinment in appoinmentList)
        {
            publicUserProfile = publicUserProfileController.fetchPublicUserNameById(appoinment.PublicUserProfileId);
            var name = publicUserProfile.FirstName + " " + publicUserProfile.LastName;

            frontAppoinmentList.Add(new
            {
                id = appoinment.Id.ToString(),
                title = name,
                start = appoinment.UtcStartTime,
                end = appoinment.UtcEndTime
            });

        }

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(frontAppoinmentList);
        var msg = String.Format("<script>loadCal('{0}');</script>", json);

        //ClientScript.RegisterStartupScript(GetType(), "hwa", msg, true);
        ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", msg, false);

    }

    protected void btnmonthly_Click(object sender, EventArgs e)
    {
        getAppointments();
    }

I have my JS to catch the JSON and load the events as,

function loadCal(eventList){
    eventList = $.parseJSON(eventList);
    alert(JSON.stringify(eventList));

        for (var j = 0; j < eventList.length; j++) {

        eventList[j].start = new Date(parseInt(eventList[j].start.replace("/Date(", "").replace(")/",""), 10));
        eventList[j].end = new Date(parseInt(eventList[j].end.replace("/Date(", "").replace(")/",""), 10));


    };
    alert(JSON.stringify(eventList[0].start));

        for (var j = 0; j < eventList.length; j++) {
            var eId = eventList[0].id;
            var eStart = eventList[0].start.toISOString();
            var eEnd = eventList[0].end.toISOString();
            var eTitle = eventList[0].title;
                    var event=
                    [{
                        id: eId,
                        title: eTitle,
                        start: eStart ,
                        end:eEnd

                    }];

                    $('#appCalendar').fullCalendar( 'renderEvent', event, true);
                };

   }

I'm creating the fullcalendar as this in document ready,

$('#appCalendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: ''
        },
        defaultDate: today,
        defaultView: 'month',
        editable: true

    });

The render event doesnt render any events, but if I pass this in the console, the events gets rendered.

var event=[{ id:1, title:"manoj", start:"2017-06-15T22:30:00.000Z", end:"2017-06-15T23:30:00.000Z" }];

$('#appCalendar').fullCalendar( 'renderEvent', event, true);

Which is exactly What I expect for my loadCal function to do with the json I passed. These are the values set for the event array (eTitle,eId etc) when I checked through breakpoints in loadCal.

can someone please tell me why the events are not rendering? I've been at this for hours now.

Update I changed the C# to a webmethod as,

[WebMethod(EnableSession = true)]
    public static string GetEvents()
    {
        List<Appoinment> appoinmentList = new List<Appoinment>();
        AppointmentController appointmentController = new AppointmentController();
        PublicUserProfileController publicUserProfileController = new PublicUserProfileController();
        PublicUserProfile publicUserProfile = new PublicUserProfile();
        //appoinmentList = appointmentController.fetchAppointmentByConsultent(Int32.Parse(Session["ICid"].ToString()));
        appoinmentList = appointmentController.fetchAppointmentByConsultent(3);

        var frontAppoinmentList = new List<object>();

        foreach (var appoinment in appoinmentList)
        {
            publicUserProfile = publicUserProfileController.fetchPublicUserNameById(appoinment.PublicUserProfileId);
            var name = publicUserProfile.FirstName + " " + publicUserProfile.LastName;

            frontAppoinmentList.Add(new
            {
                id = appoinment.Id.ToString(),
                title = name,
                start = appoinment.UtcStartTime,
                end = appoinment.UtcEndTime
            });

        }

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(frontAppoinmentList);
        return json;
    }

and my Jquery to,

$(document).ready(function () {
    $('#appCalendar').fullCalendar({
    eventClick: function() {
        alert('a day has been clicked!');
    }, 
        events: function (start, end, callback) {
        $.ajax({
            type: "POST",    //WebMethods will not allow GET
            url: "AppointmentDiary.aspx/GetEvents",   //url of a webmethod - example below

            //completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters 
            contentType: "application/json; charset=utf-8",  
            dataType: "json",
            success: function (doc) {
                var events = [];   //javascript event object created here
                var obj = $.parseJSON(doc.d);  //.net returns json wrapped in "d"
                $(obj).each(function () {
                        var startd=     new Date(parseInt(this.start.replace("/Date(", "").replace(")/",""), 10));
                        var endd = new Date(parseInt(this.end.replace("/Date(", "").replace(")/",""), 10));                 
                        events.push({
                        title: this.title,  //your calevent object has identical parameters 'title', 'start', ect, so this will work
                        start:startd.toISOString(), // will be parsed into DateTime object    
                        end: endd.toISOString(),
                        id: this.id
                    });
                });                     
                //if(callback) callback(events);
                //$('#appCalendar').fullCalendar( 'renderEvent',events[0], true);
                alert(JSON.stringify(events[0]));

            }
        });
        return events;
    }
   });
});

Callback becomes 'false' when this runs but I can see that the webmethod returning this in the alert after formatting the dates,

enter image description here

I'm getting the data from the aspx, I can read it in the jquery and I still cant render an even.at this point I don't know what eles to do. can you please look at my code and point out whats wrong? also I don't understand the use of (start,end,callback) in the function as I dont use that in the webmethod anyway.

2
is your loadCal(eventList) function called on click?Curiousdev
loadCal is most likely called before fullCalendar creates the calendar object. You need to restructure your js a bit to ensure the right orderAndrei

2 Answers

1
votes

I finally solved my question.

My C# method for fetching data and passing as a JSON is,

[WebMethod(EnableSession = true)]
    public static string GetEvents()
    {
        List<Appoinment> appoinmentList = new List<Appoinment>();
        AppointmentController appointmentController = new AppointmentController();
        PublicUserProfileController publicUserProfileController = new PublicUserProfileController();
        PublicUserProfile publicUserProfile = new PublicUserProfile();
        //appoinmentList = appointmentController.fetchAppointmentByConsultent(Int32.Parse(Session["ICid"].ToString()));
        appoinmentList = appointmentController.fetchAppointmentByConsultent(3);

        var frontAppoinmentList = new List<object>();

        foreach (var appoinment in appoinmentList)
        {
            publicUserProfile = publicUserProfileController.fetchPublicUserNameById(appoinment.PublicUserProfileId);
            var name = publicUserProfile.FirstName + " " + publicUserProfile.LastName;

            frontAppoinmentList.Add(new
            {
                id = appoinment.Id.ToString(),
                title = name,
                start = appoinment.UtcStartTime,
                end = appoinment.UtcEndTime
            });

        }

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(frontAppoinmentList);
        return json;
    }

My Jquery for creating the Fullcalendar and rendering the events is,

 $(document).ready(function () {

    $.ajax({
        type: "POST",
        url: "AppointmentDiary.aspx/GetEvents",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (doc) {

            var events = [];
            var docd = doc.d;


            var obj = $.parseJSON(doc.d);
            console.log(obj);
            alert(JSON.stringify(obj));
for (var j = 0; j < obj.length; j++) {

        obj[j].start = new Date(parseInt(obj[j].start.replace("/Date(", "").replace(")/",""), 10));
        obj[j].start = obj[j].start.toISOString();
        obj[j].end = new Date(parseInt(obj[j].end.replace("/Date(", "").replace(")/",""), 10));
        obj[j].end = obj[j].end.toISOString();


    };

           $('#appCalendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                eventClick: function () {

                },

                editable: false,

                events: obj //Just pass obj to events
            })
            console.log(events);

        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
});
0
votes
[{ id:1, title:"manoj", start:"2017-06-15T22:30:00.000Z", end:"2017-06-15T23:30:00.000Z" }] 

is an array. The renderEvent method expects an object. Try sending

{ id:1, title:"manoj", start:"2017-06-15T22:30:00.000Z", end:"2017-06-15T23:30:00.000Z" }

instead.

Or alternatively, use the renderEvents (note the plural) method (https://fullcalendar.io/docs/event_rendering/renderEvents/) and call it once, sending it eventList as a parameter (you will have to have tidied up the dates first in each event, as you do now, although you could actually do that on the server instead to be more efficient. Using JSON.NET as your serialiser would solve it).


But...really this is not how you are intended to load a bulk list of events with fullCalendar. It will be quite slow to do it all on the client side, and also you are loading all your events into it at once - imagine when your application has been running for some time and you have a whole year's worth or more, it will be even slower, and probably no-one will ever look at the older ones.

Instead you should create a separate server method (e.g. a WebMethod or other JSON service) which can accept a start and end date, and just return the relevant events between those dates. You tell fullCalendar the URL of this method when you start it up, something like this:

events: "Events.aspx/GetEvents"

Then, when the calendar starts, it requests from the server (via AJAX) the events only for the dates actually being displayed on the calendar at that time. When the date or the view changes, it requests an updated list for the new dates. Best of all it does this automatically with no further intervention from you. See https://fullcalendar.io/docs/event_data/events_json_feed/ for more details of this approach.

N.B. If you can't quite get your server method to conform to the requirements of the direct JSON feed, you can use a JavaScript function as an intermediary to alter the format of the parameters and/or alter the format of the returned data before passing it to fullCalendar. See https://fullcalendar.io/docs/event_data/events_function/

If you implement one of these solutions it will be much easier to manage the events on the calendar.