CRUD Operations On AngularUI Calendar

Hi Everyone!

Thanks for the recommendations for my previous post, Implementing Event Scheduling in Angular UI Calendar. In this tutorial, I am going to explain about implementing the  CRUD operations on UI Calendar. If you are new to this post, please refer the above link to understand the implementation of a basic UI calendar and how to load the events data from server to display in calendar.

In this tutorial, we are using the code from the previous post. The below screenshot represents the previous application.
application

CRUD operations on Angular UI Calendar(Event Scheduling)
  1. Create a Visual Studio application (in this post, the application is created in VS 2015).
  2. See previous article to know the Calendar implementation; click here.
  3. You can find what libraries to add and how to get and display server data in UI-calendar from my previous post.
  4. I am using the same table schema and ADO.NET Data Model here.

Add Controller to display View and CRUD functions

  1. Right click on Controllers folder --> Add --> Select Empty Controller template --> name it (HomController) --> Add.
  2. Replace the previous code with the following code.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using AngularUICalendarCRUd.Models;  
    7.   
    8. namespace AngularUICalendarCRUd.Controllers  
    9. {  
    10.     public class HomeController : Controller  
    11.     {  
    12.         public ActionResult Index()  
    13.         {  
    14.             return View();  
    15.         }  
    16.         public JsonResult GetEvents()  
    17.         {  
    18.             //Here MyDatabaseEntities is our entity datacontext (see Step 4)  
    19.             using (DatabaseEntities dc = new DatabaseEntities())  
    20.             {  
    21.                 var v = dc.Events.OrderBy(a => a.StartAt).ToList();  
    22.                 return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
    23.             }  
    24.         }  
    25.         //Action for Save event  
    26.         [HttpPost]  
    27.         public JsonResult SaveEvent(Event evt)  
    28.         {  
    29.             bool status = false;  
    30.             using (DatabaseEntities dc = new DatabaseEntities())  
    31.             {  
    32.                 if (evt.EndAt != null && evt.StartAt.TimeOfDay == new TimeSpan(0, 0, 0) &&  
    33.                     evt.EndAt.TimeOfDay == new TimeSpan(0, 0, 0))  
    34.                 {  
    35.                     evt.IsFullDay = true;  
    36.                 }  
    37.                 else  
    38.                 {  
    39.                     evt.IsFullDay = false;  
    40.                 }  
    41.   
    42.                 if (evt.EventID > 0)  
    43.                 {  
    44.                     var v = dc.Events.Where(a => a.EventID.Equals(evt.EventID)).FirstOrDefault();  
    45.                     if (v != null)  
    46.                     {  
    47.                         v.Title = evt.Title;  
    48.                         v.Description = evt.Description;  
    49.                         v.StartAt = evt.StartAt;  
    50.                         v.EndAt = evt.EndAt;  
    51.                         v.IsFullDay = evt.IsFullDay;  
    52.                     }  
    53.                 }  
    54.                 else  
    55.                 {  
    56.                     dc.Events.Add(evt);  
    57.                 }  
    58.                 dc.SaveChanges();  
    59.                 status = true;  
    60.             }  
    61.             return new JsonResult { Data = new { status = status } };  
    62.         }  
    63.         [HttpPost]  
    64.         public JsonResult DeleteEvent(int eventID)  
    65.         {  
    66.             bool status = false;  
    67.             using (DatabaseEntities dc = new DatabaseEntities())  
    68.             {  
    69.                 var v = dc.Events.Where(a => a.EventID.Equals(eventID)).FirstOrDefault();  
    70.                 if (v != null)  
    71.                 {  
    72.                     dc.Events.Remove(v);  
    73.                     dc.SaveChanges();  
    74.                     status = true;  
    75.                 }  
    76.             }  
    77.             return new JsonResult { Data = new { status = status } };  
    78.         }  
    79.     }  
    80. }  
  3. SaveEvent saves the event data to database. DeleteEvent deletes the event data from the database.
  4. Index action is used to render the Index View.
  5. Make the below changes in _Layout.cshtml page, in Shared folder.
    1. <!DOCTYPE html>  
    2. <html>  
    3. <head>  
    4.     <meta charset="utf-8" />  
    5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    6.     <title>@ViewBag.Title - My ASP.NET Application</title>  
    7.     <script src="~/Scripts/modernizr-2.6.2.js"></script>  
    8. </head>  
    9. <body>   
    10.     <div class="container body-content">  
    11.         @RenderBody()  
    12.         <hr />  
    13.         <footer>  
    14.             <p>© @DateTime.Now.Year - My ASP.NET Application</p>  
    15.         </footer>  
    16.     </div>  
    17. </body>  
    18. </html>  

Add View to display the UI

  1. Right click on Index action in the HomeController.cs file --> Add --> name it (Index) --> Add.
  2. Replace the Index.cshtml page code with the below code.
    1. @{  
    2.     ViewBag.Title = "Index";  
    3. }  
    4. <h2>Angular UI calender Events Scheduling CRUD operations</h2>  
    5. <!--Styles for UI calender-->  
    6. <link href="~/Content/fullcalendar.css" rel="stylesheet" />  
    7. <link href="~/Content/bootstrap.css" rel="stylesheet" />  
    8. <!--Angualar script libraries-->  
    9. <script src="~/Scripts/moment.js"></script>  
    10. <script src="~/Scripts/jquery-1.11.3.js"></script>  
    11. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>  
    12. <script src="~/Scripts/calendar.js"></script>  
    13. <script src="~/Scripts/fullcalendar.js"></script>  
    14. <script src="~/Scripts/gcal.js"></script>  
    15. <!--Current application Scripts-->  
    16. <script src="~/Scripts/myscript.js"></script>  
    17. <!--Bootstrap Angular UI Modal popup script library-->  
    18. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.2/ui-bootstrap-tpls.min.js"></script>  
    19. @* HTML *@  
    20. <div ng-app="myapp" ng-controller="CalenderController">  
    21.      <!--Angular template for modal dialog code structure starts here-->  
    22.     <script type="text/ng-template" id="modalContent.html">  
    23.         <div class="modal-header">  
    24.             <h3 class="modal-title">Events</h3>  
    25.         </div>  
    26.         <div class="modal-body">  
    27.             <div style="color:red">{{Message}}</div>  
    28.             <div class="form-group">  
    29.                 <label>Event Title : </label>  
    30.                 <input type="text" ng-model="NewEvent.Title" autofocus class="form-control" />  
    31.             </div>  
    32.             <div class="form-group">  
    33.                 <label>Description : </label>  
    34.                 <input type="text" ng-model="NewEvent.Description" class="form-control" />  
    35.             </div>  
    36.             <div class="form-group">  
    37.                 <label>Time Slot : </label>  
    38.                 <span>{{NewEvent.StartAt}} - {{NewEvent.EndAt}}</span>  
    39.             </div>  
    40.         </div>  
    41.         <div class="modal-footer">  
    42.             <button class="btn btn-primary" type="button" ng-click="ok()">Save</button>  
    43.             <button class="btn btn-danger" type="button" ng-show="NewEvent.EventID > 0" ng-click="delete()">Delete</button>  
    44.             <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>  
    45.   
    46.         </div>  
    47.         <!--Angular modal dialog code ends here-->  
    48.     </script>  
    49.     <div class="row">  
    50.         <div class="col-md-12">  
    51.             <!--this element displays the UI-caledar-->  
    52.             <div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>  
    53.         </div>        
    54.     </div>  
    55. </div>  
  3. I am using Bootstrap Angular UI Modal popup to Create, Edit, and Delete the events created in the UI calendar.

Add Script for Calendar Functionality

  1. Right click on Scripts folder --> Add --> JavaScript file.
  2. Add below script code for UI calendar display and CRUD operations.
    1. //ui.calendar --> for caledar control  
    2. //ui.bootstrap  --> for bootstrap angualr UI modal popup  
    3. var app = angular.module('myapp', ['ui.calendar''ui.bootstrap']);  
    4. app.controller('CalenderController', ['$scope''$http''uiCalendarConfig''$uibModal'function ($scope, $http, uiCalendarConfig, $uibModal) {      
    5.     $scope.SelectedEvent = null;  
    6.     var isFirstTime = true;  
    7.     $scope.events = [];  
    8.     $scope.eventSources = [$scope.events];  
    9.   
    10.     $scope.NewEvent = {};  
    11.     //this function for get datetime from json date  
    12.     function getDate(datetime) {  
    13.         if (datetime != null) {  
    14.             var mili = datetime.replace(/\/Date\((-?\d+)\)\//, '$1');  
    15.             return new Date(parseInt(mili));  
    16.         }  
    17.         else {  
    18.             return "";  
    19.         }  
    20.     }  
    21.     // this function clears clender enents  
    22.     function clearCalendar() {  
    23.         if (uiCalendarConfig.calendars.myCalendar != null) {  
    24.             uiCalendarConfig.calendars.myCalendar.fullCalendar('removeEvents');  
    25.             uiCalendarConfig.calendars.myCalendar.fullCalendar('unselect');  
    26.         }  
    27.     }  
    28.     //Load events from server to display on caledar  
    29.     function populate() {  
    30.         clearCalendar();  
    31.         $http.get('/home/getevents', {  
    32.             cache: false,  
    33.             params: {}  
    34.         }).then(function (data) {  
    35.             $scope.events.slice(0, $scope.events.length);  
    36.             angular.forEach(data.data, function (value) {  
    37.                 $scope.events.push({  
    38.                     id : value.EventID,  
    39.                     title: value.Title,  
    40.                     description: value.Description,  
    41.                     start: new Date(parseInt(value.StartAt.substr(6))),  
    42.                     end: new Date(parseInt(value.EndAt.substr(6))),  
    43.                     allDay: value.IsFullDay,  
    44.                     stick: true  
    45.                 });  
    46.             });  
    47.         });  
    48.     }  
    49.     populate();  
    50.     //UI- calendar configuration  
    51.     $scope.uiConfig = {  
    52.         calendar: {  
    53.             height: 450,  
    54.             editable: true,  
    55.             displayEventTime: true,  
    56.             header: {  
    57.                 left: 'month,agendaWeek,agendaDay',  
    58.                 center: 'title',  
    59.                 right:'today prev,next'  
    60.             },  
    61.             timeFormat : {  
    62.                 month : ' '// for hide on month view  
    63.                 agenda: 'h:mm t'  
    64.             },  
    65.             selectable: true,  
    66.             selectHelper: true,  
    67.             select : function(start, end){  
    68.                 var fromDate = moment(start).format('YYYY/MM/DD LT');  
    69.                 var endDate = moment(end).format('YYYY/MM/DD LT');  
    70.                 $scope.NewEvent = {  
    71.                     EventID : 0,  
    72.                     StartAt : fromDate,  
    73.                     EndAt : endDate,  
    74.                     IsFullDay :false,  
    75.                     Title : '',  
    76.                     Description : ''  
    77.                 }  
    78.   
    79.                 $scope.ShowModal();  
    80.             },  
    81.             eventClick: function (event) {  
    82.                 $scope.SelectedEvent = event;  
    83.                 var fromDate = moment(event.start).format('YYYY/MM/DD LT');  
    84.                 var endDate = moment(event.end).format('YYYY/MM/DD LT');  
    85.                 $scope.NewEvent = {  
    86.                     EventID : event.id,  
    87.                     StartAt : fromDate,  
    88.                     EndAt : endDate,  
    89.                     IsFullDay :false,  
    90.                     Title : event.title,  
    91.                     Description : event.description  
    92.                 }  
    93.   
    94.                 $scope.ShowModal();  
    95.             },  
    96.             eventAfterAllRender: function () {  
    97.                 if ($scope.events.length > 0 && isFirstTime) {  
    98.                     uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);  
    99.                     isFirstTime = false;  
    100.                 }  
    101.             }  
    102.         }  
    103.     };  
    104.   
    105.     //This function shows bootstrap modal dialog  
    106.     $scope.ShowModal = function () {  
    107.         $scope.option = {  
    108.             templateUrl: 'modalContent.html',  
    109.             controller: 'modalController',  
    110.             backdrop: 'static',  
    111.             resolve: {  
    112.                 NewEvent: function () {  
    113.                     return $scope.NewEvent;  
    114.                 }  
    115.             }  
    116.         };  
    117.         //CRUD operations on Calendar starts here  
    118.         var modal = $uibModal.open($scope.option);  
    119.         modal.result.then(function (data) {  
    120.             $scope.NewEvent = data.event;  
    121.             switch (data.operation) {  
    122.                 case 'Save':            //save  
    123.                     $http({  
    124.                         method: 'POST',  
    125.                         url: '/home/SaveEvent',  
    126.                         data : $scope.NewEvent  
    127.                     }).then(function (response) {  
    128.                         if (response.data.status) {  
    129.                             populate();  
    130.                         }  
    131.                     })  
    132.                     break;  
    133.                 case 'Delete':          //delete  
    134.                     $http({  
    135.                         method: 'POST',  
    136.                         url: '/home/DeleteEvent',  
    137.                         data: {'eventID' : $scope.NewEvent.EventID }  
    138.                     }).then(function (response) {  
    139.                         if (response.data.status) {  
    140.                             populate();  
    141.                         }  
    142.                     })  
    143.                     break;  
    144.                 default:  
    145.                     break;  
    146.             }  
    147.         }, function () {  
    148.             console.log('Modal dialog closed');  
    149.         })  
    150.     }  
    151. }])  
  3. In the above code, I used $http service to connect to the Server(for save, edit, and delete operations).
  4. Add the following code to display the Bootstrap Angular UI Modal popup.
    1. // create a new controller for Bootstrap Angualr modal popup  
    2. app.controller('modalController', ['$scope''$uibModalInstance''NewEvent'function ($scope, $uibModalInstance,NewEvent) {  
    3.     $scope.NewEvent = NewEvent;  
    4.     $scope.Message = "";  
    5.     $scope.ok = function () {  
    6.         if ($scope.NewEvent.Title.trim() != "") {  
    7.             $uibModalInstance.close({event : $scope.NewEvent, operation: 'Save'});  
    8.         }  
    9.         else {  
    10.             $scope.Message = "Event title required!";  
    11.         }  
    12.     }  
    13.     $scope.delete = function () {  
    14.         $uibModalInstance.close({ event: $scope.NewEvent, operation: 'Delete' });  
    15.     }  
    16.     $scope.cancel = function () {  
    17.         $uibModalInstance.dismiss('cancel');  
    18.     }  
    19. }])  
  5. Finally, run the application and see the output in the browser.

    application

  6. To create a new event, click on any Date. Then, you get a popup like the image shown below.

    application

  7. To perform EDIT and DELETE operations, click on any event.

    application

Conclusion

I hope this article was helpful for many readers. If you recommend any suggestions, I always welcome it. You can follow me on social networks, also, for daily updates.

Up Next
    Ebook Download
    View all
    Learn
    View all