Search results

Data-binding

The Scheduler uses dataManager, which supports both RESTful JSON data services binding and local JavaScript object array binding. The dataSource property can be assigned either with the instance of dataManager or JavaScript object array collection. It supports two kinds of data binding method:

  • Local data
  • Remote data

Binding local data

To bind local JSON data to the Scheduler, you can simply assign a JavaScript object array to the dataSource option of the scheduler within the eventSettings property. The local data source can also be provided as an instance of the dataManager.

tagHelper
data.cs
@using Syncfusion.EJ2.Schedule

<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTime(2018, 2, 15)">
    <e-schedule-eventsettings dataSource="@ViewBag.datasource"></e-schedule-eventsettings>
</ejs-schedule>
public ActionResult Index()
{
    ViewBag.datasource = GetScheduleData();
    return View();
}

public List<AppointmentData> GetScheduleData()
{
    List<AppointmentData> appData = new List<AppointmentData>();
    appData.Add(new AppointmentData
    { Id = 1, Subject = "Blue Moon Eclipse", StartTime = new DateTime(2018, 2, 12, 9, 30, 0), EndTime = new DateTime(2018, 2, 12, 11, 0, 0) });
    appData.Add(new AppointmentData
    { Id = 2, Subject = "Milky Way as Melting pot", StartTime = new DateTime(2018, 2, 14, 9, 30, 0), EndTime = new DateTime(2018, 2, 14, 11, 0, 0) });
    return appData;
}
    
public class AppointmentData
{
    public int Id { get; set; }
    public string Subject { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
}

By default, dataManager uses JsonAdaptor for local data-binding.

You can also bind different field names to the default event fields as well as include additional custom fields to the event object collection which can be referred here.

Binding remote data

Any kind of remote data services can be bound to the Scheduler. To do so, create an instance of dataManager and provide the service URL to the Url option of dataManager and then assign it to the dataSource property within e-schedule-eventsettings.

Using ODataV4Adaptor

ODataV4 is a standardized protocol for creating and consuming data. Refer to the following code example to retrieve the data from ODataV4 service using the dataManager. To connect with ODataV4 service end points, it is necessary to make use of ODataV4Adaptor within dataManager.

tagHelper
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule

@{
    var dataManager = new DataManager() { 
        Url = "https://js.syncfusion.com/demos/ejservices/api/Schedule/LoadData",
        Adaptor = "ODataV4Adaptor",
        CrossDomain = true 
    };
}

<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTime(2017, 6, 11)" readonly="true">
    <e-schedule-eventsettings dataSource="dataManager" query= "new ej.data.Query().from('Events')">
    </e-schedule-eventsettings>
</ejs-schedule>
public ActionResult Index()
{
    return View();
}

Using custom adaptor

It is possible to create your own custom adaptor by extending the built-in available adaptors. The following example demonstrates the custom adaptor usage and how to add a custom field EventID for the appointments by overriding the built-in response processing using the processResponse method of the ODataV4Adaptor.

tagHelper
data.cs
@using Syncfusion.EJ2.Schedule

@{
    var dataManager = new DataManager() {
        Url = "https://ej2services.syncfusion.com/development/web-services/odata/",
        Adaptor = "CustomAdaptor",
        CrossDomain = true
    };
}

<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTime(2017, 6, 11)" readonly="true">
    <e-schedule-eventsettings dataSource="dataManager" query= "new ej.data.Query().from('Events')">
    </e-schedule-eventsettings>
</ejs-schedule>

<script type="text/javascript">
    class CustomAdaptor extends ej.data.ODataV4Adaptor {
        processResponse() {
            var i = 0;
            // calling base class processResponse function
            var original = super.processResponse.apply(this, arguments);
            // adding employee id
            original.forEach( function (item) { item['EmpID'] = ++i});
            return  original;
        }
    }
</script>
public ActionResult Index()
{
    return View();
}

Loading data via AJAX post

You can bind the event data through external ajax request and assign it to the dataSource property of Scheduler. In the following code example, we have retrieved the data from server with the help of ajax request and assigned the resultant data to the dataSource property of Scheduler within the onSuccess event of Ajax.

tagHelper
data.cs
@using Syncfusion.EJ2.Schedule

<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTime(2017, 6, 11)" readonly="true">
    <e-schedule-eventsettings dataSource="dataManager">
    </e-schedule-eventsettings>
</ejs-schedule>

<script type="text/javascript">
    var ajax = new ej.base.Ajax('/Home/GetData', 'GET', false);
    ajax.send();
    ajax.onSuccess = function (data) {
        var dataManager = value;
    }
</script>
public ActionResult Index()
{
    return View();
}

Definition for the controller method GetData can be referred here.

Passing additional parameters to the server

To send an additional custom parameter to the server-side post, you need to make use of the addParams method of query. Now, assign this query object with additional parameters to the queryproperty of Scheduler.

tagHelper
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule

@{
    var dataManager = new DataManager() {
        Url = "https://ej2services.syncfusion.com/development/web-services/odata/",
        Adaptor = "ODataV4Adaptor",
        CrossDomain = true
    };
}

<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTime(2017, 6, 11)" readonly="true">
    <e-schedule-eventsettings dataSource="dataManager" query= "new ej.data.Query().from('Events').addParams('readOnly', 'true')">
    </e-schedule-eventsettings>
</ejs-schedule>
public ActionResult Index()
{
    return View();
}

The parameters added using the query property will be sent along with the data request sent to the server on every scheduler actions.

Handling failure actions

During the time of Scheduler interacting with server, there are chances that some server-side exceptions may occur. You can acquire those error messages or exception details in client-side using the actionFailure event of Scheduler.

tagHelper
data.cs
@using Syncfusion.EJ2

@{
    var dataManager = new DataManager() {
        Url = "http://some.com/invalidUrl",
        Adaptor = "UrlAdaptor",
        CrossDomain = true 
    };
}

<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTime(2017, 6, 11)" actionFailure="onActionFailure">
    <e-schedule-eventsettings dataSource="dataManager">
    </e-schedule-eventsettings>
</ejs-schedule>

<script type="text/javascript">
    function onActionFailure(args) {
        var scheduleObj = document.getElementById('schedule').ej2_instances[0];
        var span = document.createElement('span');
        scheduleObj.element.parentNode.insertBefore(span, scheduleObj.element);
        span.style.color = '#FF0000';
        span.innerHTML = 'Server exception: 404 Not found';
    }
</script>
public ActionResult Index()
{
    return View();
}

The argument passed to the actionFailure event contains the error details returned from the server.

Scheduler CRUD actions

The CRUD (Create, Read, Update and Delete) actions can be performed easily on Scheduler appointments using the various adaptors available within the dataManager. Most preferably, we will be using UrlAdaptor for performing CRUD actions on scheduler appointments.

@using Syncfusion.EJ2

@{
    var dataManager = new DataManager() {
        Url = "Home/GetData",
        Adaptor = "UrlAdaptor",
        CrudUrl = "Home/UpdateData",
        CrossDomain = true
    };
}

<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTime(2017, 6, 5)">
    <e-schedule-eventsettings dataSource="dataManager">
    </e-schedule-eventsettings>
</ejs-schedule>

The server-side controller code to handle the CRUD operations are as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScheduleSample.Models;

namespace ScheduleSample.Controllers
{
    public class HomeController : Controller
    {
        ScheduleDataDataContext db = new ScheduleDataDataContext();
        public ActionResult Index()
        {
            return View();
        }  
        public JsonResult LoadData()  // Here we get the Start and End Date and based on that can filter the data and return to Scheduler
        {
            var data = db.ScheduleEventDatas.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult UpdateData(EditParams param)
        {
            if (param.action == "insert" || (param.action == "batch" && param.added != null)) // this block of code will execute while inserting the appointments
            {
                var value = (param.action == "insert") ? param.value : param.added[0];
                int intMax = db.ScheduleEventDatas.Select(x => x.Id).DefaultIfEmpty(0).Max();
                DateTime startTime = Convert.ToDateTime(value.StartTime);
                DateTime endTime = Convert.ToDateTime(value.EndTime);
                ScheduleEventData appointment = new ScheduleEventData()
                {
                    Id = intMax + 1,
                    StartTime = startTime,
                    EndTime = endTime,
                    Subject = value.Subject,
                    IsAllDay = value.IsAllDay,
                    StartTimezone = value.StartTimezone,
                    EndTimezone = value.EndTimezone,
                    RecurrenceRule = value.RecurrenceRule,
                    RecurrenceID = value.RecurrenceID,
                    RecurrenceException = value.RecurrenceException
                };
                db.ScheduleEventDatas.InsertOnSubmit(appointment);
                db.SubmitChanges();
            }
            if (param.action == "update" || (param.action == "batch" && param.changed != null)) // this block of code will execute while updating the appointment
            {
                var value = (param.action == "update") ? param.value : param.changed[0];
                var filterData = db.ScheduleEventDatas.Where(c => c.Id == Convert.ToInt32(value.Id));
                if (filterData.Count() > 0)
                {
                    DateTime startTime = Convert.ToDateTime(value.StartTime);
                    DateTime endTime = Convert.ToDateTime(value.EndTime);
                    ScheduleEventData appointment = db.ScheduleEventDatas.Single(A => A.Id == Convert.ToInt32(value.Id));
                    appointment.StartTime = startTime;
                    appointment.EndTime = endTime;
                    appointment.StartTimezone = value.StartTimezone;
                    appointment.EndTimezone = value.EndTimezone;
                    appointment.Subject = value.Subject;
                    appointment.IsAllDay = value.IsAllDay;
                    appointment.RecurrenceRule = value.RecurrenceRule;
                    appointment.RecurrenceID = value.RecurrenceID;
                    appointment.RecurrenceException = value.RecurrenceException;
                }
                db.SubmitChanges();
            }
            if (param.action == "remove" || (param.action == "batch" && param.deleted != null)) // this block of code will execute while removing the appointment
            {
                if (param.action == "remove")
                {
                    int key = Convert.ToInt32(param.key);
                    ScheduleEventData appointment = db.ScheduleEventDatas.Where(c => c.Id == key).FirstOrDefault();
                    if (appointment != null) db.ScheduleEventDatas.DeleteOnSubmit(appointment);
                }
                else
                {
                    foreach (var apps in param.deleted)
                    {
                        ScheduleEventData appointment = db.ScheduleEventDatas.Where(c => c.Id == apps.Id).FirstOrDefault();
                        if (apps != null) db.ScheduleEventDatas.DeleteOnSubmit(appointment);
                    }
                }
                db.SubmitChanges();
            }
            var data = db.ScheduleEventDatas.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public class EditParams
        {
            public string key { get; set; }
            public string action { get; set; }
            public List<ScheduleEventData> added { get; set; }
            public List<ScheduleEventData> changed { get; set; }
            public List<ScheduleEventData> deleted { get; set; }
            public ScheduleEventData value { get; set; }
        }
    }
}

Configuring Scheduler with Google API service

We have assigned our custom created Google Calendar url to the DataManager and assigned the same to the Scheduler dataSource. Since the events data retrieved from the Google Calendar will be in its own object format, therefore it needs to be resolved manually within the Scheduler’s dataBinding event. Within this event, the event fields needs to be mapped properly and then assigned to the result.

tagHelper
data.cs
@using Syncfusion.EJ2

@{
    var calendarId = "5105trob9dasha31vuqek6qgp0@group.calendar.google.com";
    var publicKey = "AIzaSyD76zjMDsL_jkenM5AAnNsORypS1Icuqxg";
    var dataManager = new DataManager() { Url = "https://www.googleapis.com/calendar/v3/calendars/" + calendarId + "/events?key=" + publicKey, Adaptor = "WebApiAdaptor", CrossDomain = true };
}

<ejs-schedule id="schedule" width="100%" height="650px" selectedDate="new DateTime(2018, 11, 14)" readonly="true" dataBinding="onDataBinding">
    <e-schedule-eventsettings dataSource="dataManager">
    </e-schedule-eventsettings>
</ejs-schedule>

<script type="text/javascript">
    function onDataBinding(e) {
        var items = e.result.items;
        var scheduleData = [];
        if (items.length > 0) {
            for (var i = 0; i < items.length; i++) {
                var event = items[i];
                var when = event.start.dateTime;
                var start = event.start.dateTime;
                var end = event.end.dateTime;
                if (!when) {
                    when = event.start.date;
                    start = event.start.date;
                    end = event.end.date;
                }
                scheduleData.push({
                    Id: event.id,
                    Subject: event.summary,
                    StartTime: new Date(start),
                    EndTime: new Date(end),
                    IsAllDay: !event.start.dateTime
                });
            }
        }
        e.result = scheduleData;
    }
</script>
public ActionResult Index()
{
    return View();
}