Search results

Managing Tasks in ASP.NET MVC Gantt control

The Gantt component has options to dynamically insert, delete, and update tasks in the project. The primary key column is necessary to manage the tasks and perform CRUD operations in Gantt. To define the primary key, set the Columns.IsPrimaryKey property to true in the particular column.

Adding new tasks

Tasks can be dynamically added to the Gantt project by enabling the EditSettings.AllowAdding property.

Toolbar

A row can be added to the Gantt component from the toolbar while the EditSettings.AllowAdding property is set to true. On clicking the toolbar add icon, you should provide the task information in the add dialog.

razor
addingRow.cs
@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")).EditSettings(es=>
         es.AllowAdding(true)).Toolbar(new List<string>() { "Add" }).Render()
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Alt text

By default, the new row will be added to the top most row in the Gantt control.

Context menu

A row can also be added above, below or child of the selected row by using context menu support. For this, we need to enable the propertyenableContextMenu and inject the ContextMenu module into the Gantt control.

razor
contextMenu.cs
@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").Dependency("Predecessor").Child("SubTasks")
         ).EnableContextMenu(true).AllowSorting(true).AllowResizing(true).EditSettings(es => es.AllowAdding(true)).Render()
public ActionResult Index()
        {
            ViewBag.DataSource = GanttData.ProjectNewData();
            return View();
        }

Alt text

Using method

You can add rows to the Gantt control dynamically using the addRecord method and you can define the add position of the default new record by using the RowPosition property. You can also pass the RowIndex as an additional parameter.

  • Top of all the rows.
  • Bottom to all the existing rows.
  • Above the selected row.
  • Below the selected row.
  • As child to the selected row.
razor
addRow.cs
@Html.EJS().Button("addRecord").Content("Add Record").CssClass("e-primary").Render()
    @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")).EditSettings(es =>
         es.AllowAdding(true)).Render()
			
    <script>
	    document.getElementById('addRecord').addEventListener('click', function (args) {
            var record = {
                TaskId: 10,
                TaskName: 'Newly Added Record',
                StartDate: new Date('04/02/2019'),
                Duration: 3,
                Progress: 50
            };
            var ganttObj = document.getElementById('Gantt').ej2_instances[0];
            ganttObj.editModule.addRecord(record, 'Below', 2);
        });
	</script>
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Alt text

Editing tasks

The editing feature can be enabled in the Gantt control by enabling the EditSettings.AllowEditing and EditSettings.AllowTaskbarEditing properties.

The following editing options are available to update the tasks in the Gantt chart:

  • Cell
  • Dialog
  • Taskbar
  • Dependency links

Cell editing

By setting the edit mode to auto using the EditSettings.Mode property, the tasks can be edited through TreeGrid cells by double-clicking.

The following code example shows you how to enable the cell editing in Gantt control.

razor
enableCellEditing.cs
@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")
                ).EditSettings(es=>es.AllowEditing(true).Mode(Syncfusion.EJ2.Gantt.EditMode.Auto)).Render()
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Note: When the edit mode is set to Auto, on performing double-click action on TreeGrid side, the cells will be changed to editable mode and on performing double-click action on chart side, the edit dialog will appear for editing the task details.

Alt text

double click action on TreeGrid side

Alt text

double click action on chart side

Dialog editing

Modify the task details through the edit dialog by setting the edit mode to Dialog.

razor
enableDialogEditing.cs
@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")
     ).EditSettings(es=>es.AllowEditing(true).Mode(Syncfusion.EJ2.Gantt.EditMode.Dialog)).Render()
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Note: In dialog editing mode, the edit dialog appears when performing double-click action on both TreeGrid or Gantt chart sides.

Alt text

Sections or tabs in dialog

In the Gantt dialog, you can define the required tabs or editing sections using the AddDialogFields and EditDialogFields properties. Every tab is defined using the Type property.

razor
add-edit dialogtab.cs
@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").ResourceInfo(
      "ResourceId").Notes("info").Dependency("Dependency")).Toolbar(new List<string>() { "Add"}).EditSettings(es=>es.AllowEditing(
        true).AllowAdding(true).Mode(Syncfusion.EJ2.Gantt.EditMode.Dialog)).Resources((IEnumerable<object>)ViewBag.projectResources).EditDialogFields(edf =>
    {
        edf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.General).HeaderText("General").Add();
        edf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.Dependency).Add();
        edf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.Resources).Add();
        edf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.Notes).Add();
    }).ResourceFields(rf => rf.Id("ResourceId").Name("ResourceName"))
    .AddDialogFields(adf=> {
        adf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.General).HeaderText("General Tab").Add();
        adf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.Dependency).Add();
    }).Render()
public IActionResult Index()
{
    ViewBag.DataSource = ganttData();
    ViewBag.projectResources = projectResources();
    return View();
}

 public static List<GanttResources> projectResources()
        {
            List<GanttResources> GanttResourcesCollection = new List<GanttResources>();

            GanttResources Record1 = new GanttResources()
            {
                ResourceId = 1,
                ResourceName = "Martin Tamer"
            };
            GanttResources Record2 = new GanttResources()
            {
                ResourceId = 2,
                ResourceName = "Rose Fuller"
            };
            GanttResources Record3 = new GanttResources()
            {
                ResourceId = 3,
                ResourceName = "Margaret Buchanan"
            };
            GanttResources Record4 = new GanttResources()
            {
                ResourceId = 4,
                ResourceName = "Fuller King"
            };
            GanttResources Record5 = new GanttResources()
            {
                ResourceId = 5,
                ResourceName = "Davolio Fuller"
            };
            GanttResources Record6 = new GanttResources()
            {
                ResourceId = 6,
                ResourceName = "Van Jack"
            };
            GanttResources Record7 = new GanttResources()
            {
                ResourceId = 7,
                ResourceName = "Fuller Buchanan"
            };
            GanttResources Record8 = new GanttResources()
            {
                ResourceId = 8,
                ResourceName = "Jack Davolio"
            };
            GanttResources Record9 = new GanttResources()
            {
                ResourceId = 9,
                ResourceName = "Tamer Vinet"
            };
            GanttResources Record10 = new GanttResources()
            {
                ResourceId = 10,
                ResourceName = "Vinet Fuller"
            };
            GanttResources Record11 = new GanttResources()
            {
                ResourceId = 11,
                ResourceName = "Bergs Anton"
            };
            GanttResources Record12 = new GanttResources()
            {
                ResourceId = 12,
                ResourceName = "Construction Supervisor"
            };
            GanttResourcesCollection.Add(Record1);
            GanttResourcesCollection.Add(Record2);
            GanttResourcesCollection.Add(Record3);
            GanttResourcesCollection.Add(Record4);
            GanttResourcesCollection.Add(Record5);
            GanttResourcesCollection.Add(Record6);
            GanttResourcesCollection.Add(Record7);
            GanttResourcesCollection.Add(Record8);
            GanttResourcesCollection.Add(Record9);
            GanttResourcesCollection.Add(Record10);
            GanttResourcesCollection.Add(Record11);
            GanttResourcesCollection.Add(Record12);
            return GanttResourcesCollection;
        }
        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 = 50,
                ResourceId = new int[] { 1 },
                info="Measure the total property area alloted for construction"
            };
            GanttDataSource Child2 = new GanttDataSource()
            {
                TaskId = 3,
                TaskName = "Perform soil test",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 50,
                ResourceId = new int[] { 2, 3, 5 },
                info= "Obtain an engineered soil test of lot where construction is planned."+
                    "From an engineer or company specializing in soil testing"
            };
            GanttDataSource Child3 = new GanttDataSource()
            {
                TaskId = 4,
                TaskName = "Soil test approval",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Dependency = "3FS",
                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 = 50,
                ResourceId = new int[] { 4 },
                info = "Develop floor plans and obtain a materials list for estimations"

            };
            GanttDataSource Child5 = new GanttDataSource()
            {
                TaskId = 7,
                TaskName = "List materials",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 50,
                Dependency="6SS",
                ResourceId = new int[] { 4, 8 },

            };
            Record2.SubTasks.Add(Child4);
            Record2.SubTasks.Add(Child5);

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

            return GanttDataSourceCollection;
        }
        public class GanttResources
        {
            public int ResourceId { get; set; }
            public string ResourceName { get; set; }
        }
        public class GanttDataSource
        {
            public int TaskId { get; set; }
            public string TaskName { get; set; }
            public string Dependency { get; set; }
            public string info { 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; }
            public int[] ResourceId { get; set; }

        }

Alt text

Tabs in Edit Dialog

Alt text

Tabs in Add Dialog

Limiting data fields in general tab

In the Gantt dialog, you can make only specific data source fields visible for editing by using the AddDialogFields and EditDialogFields properties. The data fields are defined with Type and Fields properties.

Note: You can also define the custom fields in the add/edit dialog General tab using the Fields property.

razor
customfields.cs
@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"
  ).ResourceInfo("ResourceId").Notes("info").Dependency("Dependency")).Toolbar(new List<string>() { "Add"}).EditSettings(es=>
   es.AllowEditing(true).AllowAdding(true).Mode(Syncfusion.EJ2.Gantt.EditMode.Dialog)).Resources((IEnumerable<object>)ViewBag.projectResources).Columns(col =>
    {
        col.Field("TaskId").Width(50).Add();
        col.Field("TaskName").Add();
        col.Field("isParent").HeaderText("Custom Column").Add();
        col.Field("StartDate").Add();
        col.Field("Duration").Add();
        col.Field("Progress").Add();
    }).ResourceFields(rf => rf.Id("ResourceId").Name("ResourceName")).EditDialogFields(edf =>
    {
        edf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.General).HeaderText("General").Fields(new string[] { "TaskId", "TaskName", "isParent" }).Add();
        edf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.Notes).Add();
    }).AddDialogFields(adf=> {
        adf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.General).HeaderText("General Tab").Fields(new string[] { "TaskId", "TaskName", "isParent" }).Add();
        adf.Type(Syncfusion.EJ2.Gantt.DialogFieldType.Dependency).Add();
    }).Render()
public IActionResult Index()
{
     ViewBag.DataSource = ganttData();
     ViewBag.projectResources = projectResources();
     return View();
}

 public static List<GanttResources> projectResources()
        {
            List<GanttResources> GanttResourcesCollection = new List<GanttResources>();

            GanttResources Record1 = new GanttResources()
            {
                ResourceId = 1,
                ResourceName = "Martin Tamer"
            };
            GanttResources Record2 = new GanttResources()
            {
                ResourceId = 2,
                ResourceName = "Rose Fuller"
            };
            GanttResources Record3 = new GanttResources()
            {
                ResourceId = 3,
                ResourceName = "Margaret Buchanan"
            };
            GanttResources Record4 = new GanttResources()
            {
                ResourceId = 4,
                ResourceName = "Fuller King"
            };
            GanttResources Record5 = new GanttResources()
            {
                ResourceId = 5,
                ResourceName = "Davolio Fuller"
            };
            GanttResources Record6 = new GanttResources()
            {
                ResourceId = 6,
                ResourceName = "Van Jack"
            };
            GanttResources Record7 = new GanttResources()
            {
                ResourceId = 7,
                ResourceName = "Fuller Buchanan"
            };
            GanttResources Record8 = new GanttResources()
            {
                ResourceId = 8,
                ResourceName = "Jack Davolio"
            };
            GanttResources Record9 = new GanttResources()
            {
                ResourceId = 9,
                ResourceName = "Tamer Vinet"
            };
            GanttResources Record10 = new GanttResources()
            {
                ResourceId = 10,
                ResourceName = "Vinet Fuller"
            };
            GanttResources Record11 = new GanttResources()
            {
                ResourceId = 11,
                ResourceName = "Bergs Anton"
            };
            GanttResources Record12 = new GanttResources()
            {
                ResourceId = 12,
                ResourceName = "Construction Supervisor"
            };
            GanttResourcesCollection.Add(Record1);
            GanttResourcesCollection.Add(Record2);
            GanttResourcesCollection.Add(Record3);
            GanttResourcesCollection.Add(Record4);
            GanttResourcesCollection.Add(Record5);
            GanttResourcesCollection.Add(Record6);
            GanttResourcesCollection.Add(Record7);
            GanttResourcesCollection.Add(Record8);
            GanttResourcesCollection.Add(Record9);
            GanttResourcesCollection.Add(Record10);
            GanttResourcesCollection.Add(Record11);
            GanttResourcesCollection.Add(Record12);
            return GanttResourcesCollection;
        }
        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>(),
                isParent= true
            };
            GanttDataSource Child1 = new GanttDataSource()
            {
                TaskId = 2,
                TaskName = "Identify site location",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 50,
                ResourceId = new int[] { 1 },
                info="Measure the total property area alloted for construction"
            };
            GanttDataSource Child2 = new GanttDataSource()
            {
                TaskId = 3,
                TaskName = "Perform soil test",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Progress = 50,
                ResourceId = new int[] { 2, 3, 5 },
                info= "Obtain an engineered soil test of lot where construction is planned."+
                    "From an engineer or company specializing in soil testing"
            };
            GanttDataSource Child3 = new GanttDataSource()
            {
                TaskId = 4,
                TaskName = "Soil test approval",
                StartDate = new DateTime(2019, 04, 02),
                Duration = 4,
                Dependency = "3FS",
                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>(),
                isParent= true
            };
            GanttDataSource Child4 = new GanttDataSource()
            {
                TaskId = 6,
                TaskName = "Develop floor plan for estimation",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 50,
                ResourceId = new int[] { 4 },
                info = "Develop floor plans and obtain a materials list for estimations"

            };
            GanttDataSource Child5 = new GanttDataSource()
            {
                TaskId = 7,
                TaskName = "List materials",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 50,
                Dependency="6SS",
                ResourceId = new int[] { 4, 8 },

            };
            Record2.SubTasks.Add(Child4);
            Record2.SubTasks.Add(Child5);

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

            return GanttDataSourceCollection;
        }
        public class GanttResources
        {
            public int ResourceId { get; set; }
            public string ResourceName { get; set; }
        }
        public class GanttDataSource
        {
            public int TaskId { get; set; }
            public string TaskName { get; set; }
            public string Dependency { get; set; }
            public bool isParent { get; set; }
             public string info { 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; }
            public int[] ResourceId { get; set; }

        }

The following screenshot show the output of above code example.

Alt text

Taskbar editing

Modify the task details through user interaction such as resizing and dragging the taskbar by enabling the AllowTaskbarEditing property.

razor
enableTaskbarEditing.cs
@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")).EditSettings(es =>
         es.AllowTaskbarEditing(true)).Render()
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Prevent editing for specific tasks

On taskbar edit action, the TaskbarEditing event will be triggered. You can prevent the taskbar from editing using the TaskbarEditing event. This can be done by setting cancel property of TaskbarEditing event argument to true. And we can hide the taskbar editing indicators like taskbar resizer, progress resizer and connector points by using QueryTaskbarInfo event. The following code example shows how to achieve this.

razor
preventTaskbarEditing.cs
@Html.EJS().Gantt("Gantt").DataSource((IEnumerable<object>)ViewBag.DataSource).Height("450px").TaskbarEditing("taskbarEditing").TaskFields(
        ts => ts.Id("TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").Child("SubTasks")
        ).EditSettings(es => es.AllowTaskbarEditing(true)).QueryTaskbarInfo("queryTaskbarInfo").Render()
        
    <script>
        function taskbarEditing(args) {
           if (args.data.TaskId == 4) // We can't edit Task Id 4
                args.cancel = true;
        }
        function queryTaskbarInfo(args) {
            if (args.data.TaskId == 6) {
                args.taskbarElement.className += ' e-preventEdit' // Taskbar editing indicators are disabled
            }
        }
    </script>

    <style>
        .e-gantt-chart .e-preventEdit .e-right-resize-gripper,
        .e-gantt-chart .e-preventEdit .e-left-resize-gripper,
        .e-gantt-chart .e-preventEdit .e-progress-resize-gripper,
        .e-gantt-chart .e-preventEdit .e-left-connectorpoint-outer-div,
        .e-gantt-chart .e-preventEdit .e-right-connectorpoint-outer-div {
                         display: none;
        }
    </style>
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Task dependencies

In the Gantt control, you can update the dependencies between the tasks and link the tasks interactively. The task dependencies can be mapped from the data source using the Dependency property.

You can update the task dependencies using the following ways:

  • Mouse interactions: Using connector points in the taskbar, you can perform drag and drop action to create task dependency links.
  • Edit dialog: Create or remove the task dependencies using the Dependency tab in the edit dialog.
  • Cell editing: Create or remove the task links using cell editing.

The following code example demonstrates how to enable task dependency editing in the Gantt chart using the EditSettings property.

razor
mouse-interactions.cs
@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").Dependency("Dependency")
    ).EditSettings(es=>es.AllowEditing(true).AllowTaskbarEditing(true).Mode(Syncfusion.EJ2.Gantt.EditMode.Auto)).Render()
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 = 50
            };
            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,
                Dependency = "3FS",
                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 = 50
            };
            GanttDataSource Child5 = new GanttDataSource()
            {
                TaskId = 7,
                TaskName = "List materials",
                StartDate = new DateTime(2019, 04, 04),
                Duration = 3,
                Progress = 50,
                Dependency="6SS"
            };
            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 string Dependency { 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; }
        }

Alt text

Updating with mouse interaction action

Alt text

Updating with cell Edit

Alt text

Updating with Dialog

Note: When the edit mode is set to Auto, on performing double-click action on TreeGrid side, the cells will be changed to editable mode and on performing double-click action on chart side, the edit dialog will appear for editing the task details.

Update task values using method

Tasks’ value can be dynamically updated by using the updateRecordById method. You can call this method on any custom action. The following code example shows how to use this method to update a task.

NOTE: Using the updateRecordById method, you cannot update the task ID value.

razor
updateRecordById.cs
@Html.EJS().Button("updateRecord").Content("Update Record").CssClass("e-primary").Render()
    @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")).EditSettings(es =>
         es.AllowEditing(true)).Render()
		
	<script>
        document.getElementById('updateRecord').addEventListener('click', function (args) {
            var ganttObj = document.getElementById('Gantt').ej2_instances[0];
            var data = {
                TaskId: 3,
                TaskName: 'Updated by index value',
                StartDate: new Date('04/02/2019'),
                Duration: 4,
                Progress: 50
            };
            ganttObj.updateRecordByID(data);
        });
    </script>
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Cell edit type and its params

The columns.editType is used to define the edit type for any particular column. You can set the columns.editType based on data type of the column.

  • numericedit - NumericTextBox component for integers, double, and decimal data types.
  • defaultedit - TextBox component for string data type.
  • dropdownedit - DropDownList component to show all unique values related to that field.
  • booleanedit - CheckBox component for boolean data type.
  • datepickeredit - DatePicker component for date data type.
  • datetimepickeredit - DateTimePicker component for date time data type.

Also, you can customize the behavior of the editor component through the columns.edit.params.

The following table describes cell edit type component and their corresponding edit params of the column.

Edit Type Component Example
numericedit NumericTextBox params: { decimals: 2, value: 5 }
dropdownedit DropDownList params: { value: ‘Germany’ }
booleanedit Checkbox params: { checked: true}
datepickeredit DatePicker params: { format:‘dd.MM.yyyy’ }
datetimepickeredit DateTimePicker params: { value: new Date() }
razor
editParams.cs
@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")
         ).Columns(col =>
                {
                    col.Field("TaskId").Add();
                    col.Field("TaskName").HeaderText("Task Name").Add();
                    col.Field("StartDate").Add();
                    col.Field("Duration").EditType("numericedit").Edit(new { @params = new { min = 1 } }).ValueAccessor("durationFormat").Add();
                    col.Field("Progress").EditType("numericedit").Edit(new { @params = new Syncfusion.EJ2.Inputs.NumericTextBox() {ShowSpinButton=false} }).Add();
                }).EditSettings(es=>es.AllowEditing(true)).Render()

<script>
    function durationFormat(field, data, column) {
        return data[field];
    }
</script>
public IActionResult Index()
        {
            ViewBag.DataSource = GanttData.ProjectNewData();
            return View();
        }

Alt text

Cell Edit Template

The cell edit template is used to create a custom component for a particular column by invoking the following functions:

  • create - It is used to create the element at the time of initialization.
  • write - It is used to create the custom component or assign default value at the time of editing.
  • read - It is used to read the value from the component at the time of save.
  • destroy - It is used to destroy the component.
razor
editTemplate.cs
@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")
         ).Columns(col =>
                {
                    col.Field("TaskId").Add();
                    col.Field("TaskName").HeaderText("Task Name").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Add();
                    col.Field("StartDate").Add();
                    col.Field("Duration").Add();
                    col.Field("Progress").Add();
                }).EditSettings(es=>es.AllowEditing(true)).Render()
    <script>
        var elem;
        var dropdownlistObj;

        function create(args) {
            elem = document.createElement('input');
            return elem;
        }

        function write(args) {
            var gantt = document.getElementById("Gantt").ej2_instances[0];
            dropdownlistObj = new ej.dropdowns.DropDownList({
                dataSource: gantt.treeGrid.grid.dataSource,
                fields: { value: 'TaskName' },
                value: args.rowData[args.column.field],
                floatLabelType: 'Auto',
            });
            dropdownlistObj.appendTo(elem);
        }

        function destroy() {
            dropdownlistObj.destroy();
        }

        function read(args) {
            return dropdownlistObj.value;
        }
</script>
public IActionResult Index()
        {
            ViewBag.DataSource = GanttData.ProjectNewData();
            return View();
        }

Alt text

Disable editing for particular column

You can disable editing for particular columns, by using the columns.allowEditing property.

In the following demo, editing is disabled for the TaskName column.

razor
disableEditing.cs
@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")
         ).Columns(col =>
                {
                    col.Field("TaskId").Add();
                    col.Field("TaskName").HeaderText("Task Name").AllowEditing(false).Add();
                    col.Field("StartDate").Add();
                    col.Field("Duration").Add();
                    col.Field("Progress").Add();
                }).EditSettings(es=>es.AllowEditing(true)).Render()
public IActionResult Index()
        {
            ViewBag.DataSource = GanttData.ProjectNewData();
            return View();
        }

Maintaining data in server

All the modified data in Gantt control can be maintained in the database using RESTful web services.

All the CRUD operations in the gantt are done through DataManager. The DataManager has an option to bind all the CRUD related data in server-side.

In the below section, we have explained how to get the edited data details on the server-side using the UrlAdaptor.

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
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("/Home/UrlDatasource").Adaptor("UrlAdaptor")
}).Render()
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 });
        }

We can also do CRUD operations over Gantt data and save the changes to database. By using BatchUrl property of DataManager, we can communicate with the controller method to update the data source on CRUD operation. In gantt CRUD actions on task are dependent with other tasks. For example on editing the child record on chart side, corresponding parent item also will get affect and predecessor dependency task as well get affected. So in Gantt all the CRUD operations are considered to be batch editing where you will get all the affected records as collection. Please check the below code snippet to assign controller method to this property.

razor
UrlAdaptor.cs
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("/Home/UrlDatasource").Adaptor("UrlAdaptor").BatchUrl("Home/BatchSave");
}).Render()
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 ActionResult BatchSave([FromBody]ICRUDModel<GanttData> data)
        {

            List<GanttData> uAdded = new List<GanttData>();
            List<GanttData> uChanged = new List<GanttData>();
            List<GanttData> uDeleted = new List<GanttData>();
            //...
             return Json(new { addedRecords = uAdded, changedRecords = uChanged, deletedRecords = uDeleted });
        }

This server method will be triggered for all the CRUD operations like adding, editing and deleting actions. We can handle those each operations separately inside this method with corresponding data received in this method argument. Also, when using the UrlAdaptor, you need to return the data as JSON from the controller action and the JSON object must contain a property as result with dataSource as its value and one more property count with the dataSource total records count as its value.

Insert action

Using the added argument of the BatchUrl method we can insert the newly added row to database and return the same to client side. please find the below code example for details.

razor
UrlAdaptor.cs
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("/Home/UrlDatasource").Adaptor("UrlAdaptor").BatchUrl("Home/BatchSave");
}).Render()
GanttDataSourceEntities db = new GanttDataSourceEntities();     
public ActionResult BatchSave([FromBody]ICRUDModel<GanttData> data)
        {

            List<GanttData> uAdded = new List<GanttData>();

            //Performing insert operation
            if (data.added != null && data.added.Count() > 0)
            {
                foreach (var rec in data.added)
                {
                    uAdded.Add(this.Create(rec));
                }
            }
            return Json(new { addedRecords = uAdded });
            //...
        }
          public GanttData Create(GanttData value)
        {
            db.GanttDatas.Add(value);
            db.SaveChanges();
            return value;
        }

Editing action

Using the changed argument of the BatchUrl method we can update the modified records to database and return the same to client side. please find the below code example for details.

razor
UrlAdaptor.cs
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("/Home/UrlDatasource").Adaptor("UrlAdaptor").BatchUrl("Home/BatchSave");
}).Render()
GanttDataSourceEntities db = new GanttDataSourceEntities();     
public ActionResult BatchSave([FromBody]ICRUDModel<GanttData> data)
        {

            List<GanttData> uChanged = new List<GanttData>();

            //Performing update operation
            if (data.changed != null && data.changed.Count() > 0)
            {
                foreach (var rec in data.changed)
                {
                    uChanged.Add(this.Edit(rec));
                }
            }
             return Json(new { changedRecords = uChanged });
            //...
        }
         public GanttData Edit(GanttData value)
        {
            GanttData result = db.GanttDatas.Where(currentData => currentData.TaskId == value.TaskId).FirstOrDefault();
            if (result != null)
            {
                result.TaskId = value.TaskId;
                result.TaskName = value.TaskName;
                result.StartDate = value.StartDate;
                result.EndDate = value.EndDate;
                result.Duration = value.Duration;
                result.Progress = value.Progress;
                result.Predecessor = value.Predecessor;
                db.SaveChanges();
                return result;
            }
            else
            {
                return null;
            }
        }

Delete action

Using the deleted argument of the BatchUrl method we can remove the deleted records from database and return the same to client side. on deleting the record we need to remove its corresponding child records as well if it exist from the data base. please find the below code example for details.

razor
UrlAdaptor.cs
@Html.EJS().Gantt("Gantt").DataSource(dataManager =>
{
  dataManager.Url("/Home/UrlDatasource").Adaptor("UrlAdaptor").BatchUrl("Home/BatchSave");
}).Render()
GanttDataSourceEntities db = new GanttDataSourceEntities();     
public ActionResult BatchSave([FromBody]ICRUDModel<GanttData> data)
        {

           List<GanttData> uDeleted = new List<GanttData>();

            //Performing delete operation
            if (data.deleted != null && data.deleted.Count() > 0)
            {
                foreach (var rec in data.deleted)
                {
                    uDeleted.Add(this.Delete(rec.TaskId));
                }
            }
            return Json(new { deletedRecords = uDeleted });
        }
         public GanttData Delete(string value)
        {
            var result = db.GanttDatas.Where(currentData => currentData.TaskId == value).FirstOrDefault();
            db.GanttDatas.Remove(result);
            RemoveChildRecords(value);
            db.SaveChanges();
            return result;
        }
        public void RemoveChildRecords(string key)
        {
            var childList = db.GanttDatas.Where(x => x.ParentId == key).ToList();
            foreach (var item in childList)
            {
                db.GanttDatas.Remove(item);
                RemoveChildRecords(item.TaskId);
            }
        }

You can find the full sample at our GitHub repository.

Deleting tasks

A task delete option in the Gantt control can be enabled by enabling the EdiSettings.AllowDeleting property. Tasks can be deleted by clicking the delete toolbar item or using the deleteRow method. You can call this method dynamically on any custom actions like button click. The following code example shows how to enable the delete option in the Gantt control.

razor
deleteRecord.cs
@Html.EJS().Button("deleteRecord").Content("Delete Record").CssClass("e-primary").Render()
        @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")
         ).EditSettings(es => es.AllowDeleting(true)).Render()
        
		<script>
            document.getElementById('deleteRecord').addEventListener('click', function (args) {
               var ganttObj = document.getElementById('Gantt').ej2_instances[0];
               ganttObj.editModule.deleteRow();
            });
	    </script>
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

NOTE: You should select any one of the rows in the Gantt control to perform task delete action. You should set the AllowDeleting value to true to delete the record dynamically.

Delete confirmation message

Delete confirmation message is used to get the confirmation from users before deleting a task. This confirmation message can be enabled by setting the EditSettings.ShowDeleteConfirmDialog property to true.

The following code snippet explains how to enable the delete confirmation message in Gantt.

razor
deleteConfirmationDialog.cs
@Html.EJS().Gantt("Gantt").DataSource((IEnumerable<object>)ViewBag.DataSource).Height("450px").Toolbar(new List<string>() { "Delete"}
    ).TaskFields(ts => ts.Id("TaskId").Name("TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress(
        "Progress").Child("SubTasks")).EditSettings(es => es.AllowDeleting(true).ShowDeleteConfirmDialog(true)).Render()
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Alt text

Indent and Outdent

Indent and Outdent of a task are used to update the level of the task in hierarchical order of the task. It can be performed bu enabling the editSettings.allowEditing property.

Indent - Selected task can be indented to the level of task to the hierarchical order. It can be performed by using in-built context menu or toolbar items. It can also be invoked by using the indent method dynamically on any action like external button click. The following code example shows how to enable indent option in the Gantt chart.

Outdent - Selected task can be outdented to the level of task from the hierarchical order. It can be performed by using in-built context menu or toolbar items. It can also be invoked by using the outdent method dynamically on any action like external button click. The following code example shows how to enable outdent option in the Gantt chart.

razor
indentoutdent.cs
@Html.EJS().Button("indent").Content("Indent").CssClass("e-primary").Render()
@Html.EJS().Button("outdent").Content("Outdent").CssClass("e-primary").Render()
    @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")).EditSettings(es =>
         es.AllowEditing(true)).Toolbar(new List<string>() 
  { "Indent", "Outdent" }).Render()
		
	<script>
        document.getElementById('indent').addEventListener('click', function (args) {
            var ganttObj = document.getElementById('Gantt').ej2_instances[0];
            ganttObj.indent();
        });
        document.getElementById('outdent').addEventListener('click', function (args) {
            var ganttObj = document.getElementById('Gantt').ej2_instances[0];
            ganttObj.outdent();
        });
    </script>
public ActionResult Index()
{
    ViewBag.DataSource = ProjectNewData();
    return View();
}

Read-only Gantt

In Gantt, all create, update, delete operations can be disabled by set readOnly property as true. The following sample demonstrates, render Gantt chart as read only.

razor
readOnly.cs
@Html.EJS().Gantt("Gantt").DataSource((IEnumerable<object>)ViewBag.DataSource).Height("450px").Toolbar(new List<string>() 
  { "Add", "Cancel", "CollapseAll", "Delete", "Edit", "ExpandAll", "NextTimeSpan", "PrevTimeSpan", "Search", "Update" }).TaskFields(ts => ts.Id("TaskId").Name(
                "TaskName").StartDate("StartDate").EndDate("EndDate").Duration("Duration").Progress("Progress").Child("SubTasks")
                ).EnableContextMenu(true).AllowSorting(true).AllowResizing(true).ReadOnly(true).EditSettings(es=>
                es.AllowEditing(true).AllowAdding(true).AllowDeleting(true).AllowTaskbarEditing(true)).Render()
public IActionResult Index()
{
    ViewBag.DataSource = GanttData.ProjectNewData();
    return View();
}

Alt text

Alt text

Troubleshoot: Editing works only when primary key column is defined

Editing feature requires a primary key column for CRUD operations. While defining columns in Gantt using the columns property, it is mandatory that any one of the columns, must be a primary column. By default, the id column will be the primary key column. If id column is not defined, we need to enable isPrimaryKey for any one of the columns defined in the columns property.