Search results

Data Binding in ASP.NET MVC Gantt control

14 Apr 2021 / 6 minutes to read

The Gantt control uses DataManager for binding the data source, which supports both RESTful JSON data services and local JavaScript object array. The DataSource property can be assigned either with the instance of DataManager or JavaScript object array collection. The Gantt control supports binding two types of data:

  • Local data
  • Remote data

Local data

To bind local data to Gantt, you can assign a JavaScript object array to the DataSource property. The local data source can also be provided as an instance of the DataManager.

In local data binding, the data source for rendering the Gantt control is retrieved from the same application locally.

The following are the two types of data binding possible with the Gantt control:

  • Hierarchical data binding.
  • Self-referential data binding (Flat data).

Hierarchical data binding

The Child property is used to map the child records in hierarchical data.

The following code example shows how to bind the hierarchical local data into the Gantt control.

razor
hierarchyData.cs
Copied to clipboard
@Html.EJS().Gantt("Gantt").DataSource((IEnumerable<object>)ViewBag.DataSource).Height("450px").TaskFields(ts => ts.Id(
                "TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").Child("SubTasks")
                ).Render()
Copied to clipboard
public IActionResult Index()
{
    ViewBag.DataSource = ganttData();
    return View();
}

public static List<GanttDataSource> ganttData()
        {
            List<GanttDataSource> GanttDataSourceCollection = new List<GanttDataSource>();

            GanttDataSource Record1 = new GanttDataSource()
            {
                TaskId = 1,
                TaskName = "Project initiation",
                StartDate = new DateTime(2019, 04, 02),
                EndDate = new DateTime(2019, 04, 21),
                SubTasks = new List<GanttDataSource>(),
            };
            GanttDataSource Child1 = new GanttDataSource()
            {
                TaskId = 2,
                TaskName = "Identify site location",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 70,

            };
            GanttDataSource Child2 = new GanttDataSource()
            {
                TaskId = 3,
                TaskName = "Perform soil test",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 50

            };
            GanttDataSource Child3 = new GanttDataSource()
            {
                TaskId = 4,
                TaskName = "Soil test approval",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 50
            };
            Record1.SubTasks.Add(Child1);
            Record1.SubTasks.Add(Child2);
            Record1.SubTasks.Add(Child3);

            GanttDataSource Record2 = new GanttDataSource()
            {
                TaskId = 5,
                TaskName = "Project estimation",
                StartDate = new DateTime(2019, 04, 02),
                EndDate = new DateTime(2019, 04, 21),
                SubTasks = new List<GanttDataSource>()
            };
            GanttDataSource Child4 = new GanttDataSource()
            {
                TaskId = 6,
                TaskName = "Develop floor plan for estimation",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 70
            };
            GanttDataSource Child5 = new GanttDataSource()
            {
                TaskId = 7,
                TaskName = "List materials",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 50
            };
            Record2.SubTasks.Add(Child4);
            Record2.SubTasks.Add(Child5);

            GanttDataSourceCollection.Add(Record1);
            GanttDataSourceCollection.Add(Record2);

            return GanttDataSourceCollection;
        }
		
		public class GanttDataSource
        {
            public int TaskId { get; set; }
            public string TaskName { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public int? Duration { get; set; }
            public int Progress { get; set; }
            public List<GanttDataSource> SubTasks { get; set; }
        }

Self-referential data binding (Flat data)

The Gantt control can be bound with self-referential data by mapping the data source field values to the Id and ParentID properties.

  • ID field: This field contains unique values used to identify each individual task and it is mapped to the Id property.
  • Parent ID field: This field contains values that indicate parent tasks and it is mapped to the ParentID property.
razor
selfReference.cs
Copied to clipboard
@Html.EJS().Gantt("Gantt").DataSource((IEnumerable<object>)ViewBag.DataSource).Height("450px").TaskFields(ts => ts.Id(
                "TaskId").ParentId("ParentId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress")
                ).Render()
Copied to clipboard
public IActionResult Index()
{
      ViewBag.DataSource = ganttData();
      return View();
}

 public static List<GanttDataSource> ganttData()
        {
            List<GanttDataSource> GanttDataSourceCollection = new List<GanttDataSource>();
            GanttDataSourceCollection.Add(new GanttDataSource()
            {
                TaskId = 1,
                TaskName = "Project initiation",
                StartDate = new DateTime(2019, 04, 02),
                EndDate = new DateTime(2019, 04, 21),
                ParentId = null
            });
            GanttDataSourceCollection.Add(new GanttDataSource()
            {
                TaskId = 2,
                TaskName = "Identify site location",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 70,
                ParentId = 1
            });
            GanttDataSourceCollection.Add(new GanttDataSource()
            {
                TaskId = 3,
                TaskName = "Perform soil test",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 50,
                ParentId = 1
            });

            GanttDataSourceCollection.Add(new GanttDataSource()
            {
                TaskId = 4,
                TaskName = "Soil test approval",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 50,
                ParentId = 1
            });
            GanttDataSourceCollection.Add(new GanttDataSource()
            {
                TaskId = 5,
                TaskName = "Project estimation",
                StartDate = new DateTime(2019, 04, 02),
                EndDate = new DateTime(2019, 04, 21),
                ParentId = null
            });
            GanttDataSourceCollection.Add(new GanttDataSource()
            {
                TaskId = 6,
                TaskName = "Develop floor plan for estimation",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 70,
                ParentId = 5
            });
            GanttDataSourceCollection.Add(new GanttDataSource()
            {
                TaskId = 7,
                TaskName = "List materials",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 50,
                ParentId = 5
            });
            return GanttDataSourceCollection;
        }
        
        public class GanttDataSource
        {
            public int TaskId { get; set; }
            public int? ParentId { get; set; }
            public string TaskName { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public int? Duration { get; set; }
            public int Progress { get; set; }
           
        }

Remote data

To bind remote data to the Gantt component, assign service data as an instance of DataManager to the DataSource property.

razor
remoteData.cs
Copied to clipboard
@Html.EJS().Gantt("Gantt").DataSource(dataManger =>
                {
                    dataManger.Url("https://ej2services.syncfusion.com/production/web-services/api/GanttData").CrossDomain(true).Adaptor("WebApiAdaptor");
                }).Height("450px").TaskFields(ts => ts.Id("TaskId").Name("TaskName").StartDate("StartDate").Progress("Progress").Duration("Duration"
                ).Dependency("Predecessor").Child("SubTasks")).Render()
Copied to clipboard
public IActionResult Index()
{
    return View();
}

Alt text

URL Adaptor

In Gantt, we can fetch data from SQL database using ADO.NET Entity Data Model and update the changes on CRUD action to the server by using DataManager support. To communicate with the remote data we are using UrlAdaptor of DataManager property to call the server method and get back resultant data in JSON format. We can know more about UrlAdaptor from here.

Please refer the link to create the ADO.NET Entity Data Model in Visual studio,

We can define data source for Gantt as instance of DataManager using url property of DataManager. Please Check the below code snippet to assign data source to Gantt.

razor
urlAdaptor.cs
Copied to clipboard
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("/Home/UrlDatasource").Adaptor("UrlAdaptor")
}).TaskFields(ts =>
   ts.Id("TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").Child("SubTasks")
   ).Render()
Copied to clipboard
GanttDataSourceEntities db = new GanttDataSourceEntities();    
 public ActionResult UrlDatasource(DataManagerRequest dm)
        {
          
            List<GanttData>DataList = db.GanttDatas.ToList();
            var count = DataList.Count();
            return Json(new { result = DataList, count = count });
        }

Sending additional parameters to the server

We can pass additional parameters using addParams method of Query class. In server side we have inherited and shown the additional parameter value in Syncfusion DataManager class itself. We pass an additional parameter in load time using load event. We can also pass additional parameter to the CRUD model. Please Check the below code snippet to send additional parameter to Gantt.

razor
serverParameters.cs
Copied to clipboard
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("http://localhost:50039/Home/UrlDatasource").Adaptor("UrlAdaptor").BatchUrl("http://localhost:50039/Home/BatchSave");
}).Toolbar(new List<string>() 
  { "Add", "Cancel", "CollapseAll", "Delete", "Edit", "ExpandAll", "Update" }).TaskFields(ts =>
   ts.Id("TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").ParentId("ParentId")
   ).EditSettings(es=>es.AllowEditing(true).AllowAdding(true).AllowDeleting(true)).Load("load").Render()

<script>
function load(args) {
    var ganttObj = document.getElementById("Gantt").ej2_instances[0];
    ganttObj.query = new Query().addParams('ej2Gantt', "test");
</script>
Copied to clipboard
namespace URLAdaptor.Controllers
{
    public class HomeController : Controller
    {
        ...///
        //inherit the class to show age as property of DataManager
        public class Test : DataManagerRequest
        {
            public string ej2Gantt { get; set; }
        }

        public ActionResult UrlDatasource([FromBody]Test dm)
        {
            if (DataList == null)
            {
                ProjectData datasource = new ProjectData();
                DataList = datasource.GetUrlDataSource();
            }
            var count = DataList.Count();
            return Json(new { result = DataList, count = count }, JsonRequestBehavior.AllowGet);
        }

        ...///

        public class ICRUDModel<T> where T : class
        {

            public object key { get; set; }

            public T value { get; set; }

            public List<T> added { get; set; }

            public List<T> changed { get; set; }

            public List<T> deleted { get; set; }

            public IDictionary<string, object> @params { get; set; }

        }
        ...///
    }
}

Handling HTTP error

During server interaction from the Gantt, some server-side exceptions may occur, and you can acquire those error messages or exception details in client-side using the actionFailure event.

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

razor
httpError.cs
Copied to clipboard
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("http://some.com/invalidUrl")}).TaskFields(ts =>
   ts.Id("TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").ParentId("ParentId")
   ).ActionFailure("actionFailure").Render()

<script>
function actionFailure(args) {
    var ganttObj = document.getElementById("Gantt").ej2_instances[0];
    let span: HTMLElement = document.createElement('span');
    ganttObj.element.parentNode.insertBefore(span, ganttObj.element);
    span.style.color = '#FF0000'
    span.innerHTML = 'Server exception: 404 Not found';
</script>
Copied to clipboard
GanttDataSourceEntities db = new GanttDataSourceEntities();    
 public ActionResult UrlDatasource(DataManagerRequest dm)
        {
          
            List<GanttData>DataList = db.GanttDatas.ToList();
            var count = DataList.Count();
            return Json(new { result = DataList, count = count });
        }

Binding with Ajax

You can use Gantt dataSource property to bind the data source to Gantt from external Ajax request. In the below code we have fetched the data source from the server with the help of Ajax request and provided that to dataSource property by using onSuccess event of the Ajax.

razor
ajaxBinding.cs
Copied to clipboard
@Html.EJS().Button("dataBind").Content("Bind Data").CssClass("e-primary").Render()
@Html.EJS().Gantt("Gantt").TaskFields(ts =>
   ts.Id("TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").Child("SubTasks")
   ).Render()

<script>
        document.getElementById('dataBind').addEventListener('click', function (args) {
            var ganttObj = document.getElementById('Gantt').ej2_instances[0];
            var ajax = new Ajax("https://ej2services.syncfusion.com/production/web-services/api/GanttData","GET");
            ganttObj.showSpinner();
            ajax.send();
            ajax.onSuccess = function (data: string) {
            ganttObj.hideSpinner();
            ganttObj.dataSource = (JSON.parse(data)).Items;
            ganttObj.refresh();
    };
        });
    </script>
Copied to clipboard
GanttDataSourceEntities db = new GanttDataSourceEntities();    
 public ActionResult UrlDatasource(DataManagerRequest dm)
        {
          
            List<GanttData>DataList = db.GanttDatas.ToList();
            var count = DataList.Count();
            return Json(new { result = DataList, count = count });
        }

Note: If you bind the dataSource from this way, then it acts like a local dataSource. So you cannot perform any server side crud actions.

Split task

The Split-task feature allows you to split a task or interrupt the work during planned or unforeseen circumstances. We can split the task either in load time or dynamically, by defining the segments either in hierarchical or self-referential way.

Hierarchical

To split a task at load time in hierarchical way, we need to define the segment details in datasource and this field should be mapped by using the taskFields.Segments property.

Copied to clipboard
GanttDataSource Record2Child1 = new GanttDataSource()
        {
            TaskId = 3,
            TaskName = "Plan timeline",
            StartDate = new DateTime(2019, 02, 04),
            EndDate = new DateTime(2019, 02, 10),
            Duration = 10,
            Progress = 60,
            Segments = new List<GanttSegment>
            {
                new GanttSegment {StartDate = new DateTime(2019,02,04), Duration = 2},
                new GanttSegment {StartDate = new DateTime(2019,02,05), Duration = 5},
                new GanttSegment {StartDate = new DateTime(2019,02,08), Duration = 3}
            }
        };
razor
split-task.cs
Copied to clipboard
@Html.EJS().Gantt("Gantt").DataSource((IEnumerable<object>)ViewBag.DataSource).Height("450px").TaskFields(ts => ts.Id("TaskId").Name(
                "TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").Child("SubTasks").Segments("Segments")
                ).Render()
Copied to clipboard
public ActionResult SplitTasks()
        {
            ViewBag.DataSource = GanttData.SplitTasksData();
            return View();
        }

Alt text

Self-referential

We can also define segment details as a flat data and this collection can be mapped by using segmentData property. The segment id field of this collection is mapped by using the taskFields.SegmentId property.

Copied to clipboard
  GanttSegment Record1 = new GanttSegment()
        {
            segmentId = 2,
            Duration = 2,
            StartDate = new DateTime(2019, 04, 02),
        };
razor
split-selfreference.cs
Copied to clipboard
@(Html.EJS().Gantt("SplitTasks").DataSource((IEnumerable<object>)ViewBag.DataSource).SegmentData((IEnumerable<object>)ViewBag.Segment)
            .TaskFields(ts => ts.Id("TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress")
            .Dependency("Predecessor").SegmentId("segmentId").Child("SubTasks"))
            .Render())
Copied to clipboard
public ActionResult SplitTasks()
        {
            ViewBag.DataSource = GanttData.SplitTasksData();
            ViewBag.Segment = GanttData.SegmentData();
            return View();
        }

Alt text

Note: Segment id field contains id of a task which should be split at load time.

Limitations

Gantt has the support for both Hierarchical and Self-Referential data binding. When rendering the Gantt control with SQL database, we suggest you to use the Self-Referential data binding to maintain the parent-child relation. Because the complex json structure is very difficult to manage it in SQL tables, we need to write a complex queries and we have to write a complex algorithm to find out the proper record details while updating/deleting the inner level task in Gantt data source. We cannot implement both data binding for Gantt control and this is not a recommended way. If both child and parentID are mapped, the records will not render properly because, when task id of a record defined in the hierarchy structure is assigned to parent id of another record, in such case the records will not properly render. As the self-referential will search the record with particular id in flat data only, not in the inner level of records. If we map the parentID field, it will be prioritized and Gantt will be rendered based on the parentID values.