Dynamically Events Bind In Full Calendar

In this article, we will learn to Dynamically Events Bind In Full Calendar.

Full Calendar displays display your events on a nice, modern calendar script. Users can browse for your events per month, per week or per day from this calendar.

Let’s begin.

Please read this article first of all Here.

C# Code Example

Open the Models folder and make a class EventsModel and add the code in it.

public class EventsModel
{
    public string Title { get; set; }
    public DateTime DateTime { get; set; }
    public string FromTime { get; set; }
    public string ToTime { get; set; }
}

Open the app-calendar.js and add the below code in it.

var eventsDisplay = [];

var colorArr = ["#ff5722", "#9c27b0", "#e51c23", "#e91e63", "#3f51b5", "#ffc107", "#4a148c", "#009688", "#009688", "#4CAF50", "#00bcd4", "#a31d1d", "#4cb3be", "#19aa45", "#ba4e18", "#c49e15", "#e0c974", "#0883d6", "#ff5722", "#9c27b0", "#e51c23", "#e91e63", "#3f51b5", "#ffc107", "#4a148c"]

var Calendar = FullCalendar.Calendar;
var Draggable = FullCalendarInteraction.Draggable;
var containerEl = document.getElementById('external-events');
var calendarEl = document.getElementById('fc-external-drag');
var checkbox = document.getElementById('drop-remove');

$(document).ready(function () {
    debugger

    GetEvent();

    $('#external-events .fc-event').each(function () {
        // Different colors for events
        $(this).css({ 'backgroundColor': $(this).data('color'), 'borderColor': $(this).data('color') });
    });
    var colorData;
    $('#external-events .fc-event').mousemove(function () {
        colorData = $(this).data('color');
    })
    // Draggable event init
    new Draggable(containerEl, {
        itemSelector: '.fc-event',
        eventData: function (eventEl) {
            return {
                title: eventEl.innerText,
                color: colorData
            };
        }
    });
})


function GetEvent() {
    debugger
    eventsDisplay = [];
    $.ajax({
        url: "/Home/GetAllEvents",
        success: function (result) {
            if (result.IsSuccess) {
                debugger
                for (var i = 0; i < result.data.length; i++) {
                  
                        debugger
                    var startdate = combinedfullcalendartime(result.data[i].DateTime, result.data[i].FromTime);
                    var enddate = combinedfullcalendartime(result.data[i].DateTime, result.data[i].ToTime);
                        eventsDisplay.push({
                            eventID: 0,
                            title: result.data[i].Title,
                           start: startdate,
                            end: enddate,
                           color: colorArr[i],
                            //allDay: true
                        });

                    
                   

                }
            }


            GenerateCalender(eventsDisplay);
        },
        error: function (error) {
            alert('failed');
        }
    })
}

function combinedfullcalendartime(date, time) {
    debugger
    var time = time;
    time = time.split(' ');
    var newtime = time[0] + ":00";
  
    var newdate = date + "T" + newtime;
    return newdate;
}

function GenerateCalender(eventsdisplay) {
    debugger
    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;
     var calendar = new Calendar(calendarEl, {
        header: {
            left: 'prev,next today',
            center: 'title',
            right: "dayGridMonth,timeGridWeek,timeGridDay"
        },
        editable: true,
        plugins: ["dayGrid", "timeGrid", "interaction"],
        droppable: true,
        defaultDate: output,
       
        events: eventsdisplay,
       
        drop: function (info) {
            // is the "remove after drop" checkbox checked?
            if (checkbox.checked) {
                // if so, remove the element from the "Draggable Events" list
                info.draggedEl.parentNode.removeChild(info.draggedEl);
            }
        },
        viewRender: function (view, element) {

            $('.fc-center')[0].children[0].innerText = view.title.replace(new RegExp("undefined", 'g'), "");
        },
        eventDataTransform: function (event) {

            if (event.allDay) {
                event.end = moment(event.end).add(1, 'days')
            }
            return event;
        },
        eventClick: function (calEvent, jsEvent, view) {
            var events = calEvent.event._def.extendedProps;
            },
    });

    calendar.render();
    
}

Open the HomeController.cs and add the below code in it.

public JsonResult GetAllEvents()
 {
     try
     {

         IList<EventsModel> eventslist = new List<EventsModel>() {
          new EventsModel(){Title="Meeting", DateTime =DateTime.Now, FromTime="09:30 AM",ToTime="11:30 AM"},
         new EventsModel(){Title="Conference", DateTime = DateTime.Now, FromTime="10:30 AM",ToTime="12:25 AM"},
         new EventsModel(){Title="Long Event", DateTime = DateTime.Now, FromTime="07:30 PM", ToTime="11:30 PM"}
     };
       
       
         var modifiedData = eventslist.Select(d =>
             new
             {

                 DateTime = d.DateTime == null ? null : d.DateTime.ToString("yyyy-MM-dd"),
                 d.FromTime,
                 d.ToTime,
               d.Title

             }
             );

         return Json(new { IsSuccess = true, data = modifiedData }, JsonRequestBehavior.AllowGet);
     }
     catch (Exception ex)
     {

         return Json(new { IsSuccess = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
     }
 }

Open the Home.cshtml and add the below code in it.

<link href="~/Scripts/FullCalendarJs/Css/fullcalendar.min.css" rel="stylesheet" />
<link href="~/Scripts/FullCalendarJs/Css/daygrid.min.css" rel="stylesheet" />
<link href="~/Scripts/FullCalendarJs/Css/timegrid.min.css" rel="stylesheet" />
<link href="~/Scripts/FullCalendarJs/Css/app-calendar.css" rel="stylesheet" />

<div class="col s12">
    <div class="container">
        <div id="app-calendar">
            <div class="row">
                <div class="col s12">
                    <div class="card">
                        <div class="card-content">
                            <h4 class="card-title">
                                Basic Calendar
                            </h4>
                            <div id='fc-external-drag'></div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

@section scripts
{
    <script src="~/Scripts/FullCalendarJs/moment.min.js"></script>
    <script src="~/Scripts/FullCalendarJs/fullcalendar.min.js"></script>
    <script src="~/Scripts/FullCalendarJs/daygrid.min.js"></script>
    <script src="~/Scripts/FullCalendarJs/timegrid.min.js"></script>
    <script src="~/Scripts/FullCalendarJs/interaction.min.js"></script>
    <script src="~/Scripts/FullCalendarJs/app-calendar.js"></script>
}

Output:

if you have any questions or issues about this article, please let me know and more information here.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories