Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a full calendar with JSON?

I'm trying to use the fullcalendar.io plugin (in my ASP.NET MVC5 project) without success.

As I saw in the docs, I'm trying this:

function renderCalendar() {
  $('#calendar').fullCalendar({
    header: {
        left: 'prev,next, today',
        center: 'title',
        right: ''
    },
    lang: currentLangCode,
    eventLimit: true,
    eventSource :  [getEvents()]
  });
}

renderCalendar();

function getEvents() {
  var source = [{}];
  $.ajax({
    async: false,
    url: '/home/fullevents',
    data: { myParam: $('#calendar').fullCalendar('getView').visStart },
    success: function (data) {
      $(data).each(function (e, v) { 
        source.push({
          title: v.Title,
          start: v.Date,
          color: '#25427e'
        });
      });
      console.log(source);
    },
    error: function () {
      alert('could not get the data');
    },
  });
  return source;
}

The array is coming like this:

[
  {
    Date: "/Date(1448985600000)/",
    Title: "teste04"
  }
]

Am I missing something here? It throws no error in the console. It just doesn't work.

like image 496
gog Avatar asked Oct 19 '25 10:10

gog


1 Answers

Firstly you should avoid creating synchronous XHR requests as they block the UI. Browsers are single threaded so you should try and use asynchronous calls where possible.

I believe what you're trying to achieve is already part of the FullCalendar library. There is an events option which will be called when you first initialize your application and whenever you page through your calendar.

$('#calendar').fullCalendar({
    events: '/myfeed.php'
});

You just need to make sure your json is formatted according to the Event Object as outlined in FullCalendar's documentation.

Example

Below is a quick example how you can use WebApi and Fullcalendar together.

View

@section scripts{

    <script type="text/javascript">

        $(function () {

            $('#calendar').fullCalendar({
                events: '@Url.HttpRouteUrl("DefaultApi", new { controller = "Calendar" })'
            });

        });

    </script>


}

<div id="calendar">

</div>

Event Model

This matches the Event Object that Fullcalendar have outlined in their documentation.

public class Event
{

    public string Id { get; set; }

    public string Title { get; set; }

    public bool AllDay { get; set; }

    public DateTime Start { get; set; }

    public DateTime? End { get; set; }

    //
    // You can add the other properties if required
    //
}

Full calendar does not like proper case property names so we need to tell our JSON serializer to use camelcase. Add the following in your Global.asax or startup

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
    new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

Web Api Controller

public class CalendarController : ApiController
{


    public HttpResponseMessage Get(DateTime start, DateTime end)
    {
        //
        // FullCalendar will keep passing the start and end values in as you navigate through the calendar pages
        //  You should therefore use these days to determine what events you should return . Ie
        //  i.e.     var events = db.Events.Where(event => event.Start > start && event.End < end);

        //
        // Below is dummy data to show you how the event object can be serialized 
        //
        var events = new List<Event>();

        events.Add(new Event
        {
            Id = "EventOne",
            Title = "My First Event",
            AllDay = false,
            Start = DateTime.Now.AddHours(-2),
            End = DateTime.Now.AddHours(2)
        });

        return Request.CreateResponse(HttpStatusCode.OK, events, Request.GetConfiguration());

    }

}

Example Response from Controller

[{"id":"EventOne","title":"My First Event","allDay":false,"start":"2015-12-08T19:54:49.7938372+00:00"
,"end":"2015-12-08T23:54:49.7938372+00:00"}]

That should be everything you need to start using WebApi and Fullcalendar. This would obviously work just as well using MVC and return a Json result. As you page through the calendar you should notice your action being hit as the start and end days change.

Hope this helps!

like image 101
heymega Avatar answered Oct 21 '25 23:10

heymega



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!