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. namespace AngularUICalendarCRUd.Controllers
    8. {
    9. public class HomeController : Controller
    10. {
    11. public ActionResult Index()
    12. {
    13. return View();
    14. }
    15. public JsonResult GetEvents()
    16. {
    17. //Here MyDatabaseEntities is our entity datacontext (see Step 4)
    18. using (DatabaseEntities dc = new DatabaseEntities())
    19. {
    20. var v = dc.Events.OrderBy(a => a.StartAt).ToList();
    21. return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    22. }
    23. }
    24. //Action for Save event
    25. [HttpPost]
    26. public JsonResult SaveEvent(Event evt)
    27. {
    28. bool status = false;
    29. using (DatabaseEntities dc = new DatabaseEntities())
    30. {
    31. if (evt.EndAt != null && evt.StartAt.TimeOfDay == new TimeSpan(0, 0, 0) &&
    32. evt.EndAt.TimeOfDay == new TimeSpan(0, 0, 0))
    33. {
    34. evt.IsFullDay = true;
    35. }
    36. else
    37. {
    38. evt.IsFullDay = false;
    39. }
    40. if (evt.EventID > 0)
    41. {
    42. var v = dc.Events.Where(a => a.EventID.Equals(evt.EventID)).FirstOrDefault();
    43. if (v != null)
    44. {
    45. v.Title = evt.Title;
    46. v.Description = evt.Description;
    47. v.StartAt = evt.StartAt;
    48. v.EndAt = evt.EndAt;
    49. v.IsFullDay = evt.IsFullDay;
    50. }
    51. }
    52. else
    53. {
    54. dc.Events.Add(evt);
    55. }
    56. dc.SaveChanges();
    57. status = true;
    58. }
    59. return new JsonResult { Data = new { status = status } };
    60. }
    61. [HttpPost]
    62. public JsonResult DeleteEvent(int eventID)
    63. {
    64. bool status = false;
    65. using (DatabaseEntities dc = new DatabaseEntities())
    66. {
    67. var v = dc.Events.Where(a => a.EventID.Equals(eventID)).FirstOrDefault();
    68. if (v != null)
    69. {
    70. dc.Events.Remove(v);
    71. dc.SaveChanges();
    72. status = true;
    73. }
    74. }
    75. return new JsonResult { Data = new { status = status } };
    76. }
    77. }
    78. }
  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. </div>
    46. <!--Angular modal dialog code ends here-->
    47. </script>
    48. <div class="row">
    49. <div class="col-md-12">
    50. <!--this element displays the UI-caledar-->
    51. <div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
    52. </div>
    53. </div>
    54. </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. $scope.NewEvent = {};
    10. //this function for get datetime from json date
    11. function getDate(datetime) {
    12. if (datetime != null) {
    13. var mili = datetime.replace(/\/Date\((-?\d+)\)\//, '$1');
    14. return new Date(parseInt(mili));
    15. }
    16. else {
    17. return "";
    18. }
    19. }
    20. // this function clears clender enents
    21. function clearCalendar() {
    22. if (uiCalendarConfig.calendars.myCalendar != null) {
    23. uiCalendarConfig.calendars.myCalendar.fullCalendar('removeEvents');
    24. uiCalendarConfig.calendars.myCalendar.fullCalendar('unselect');
    25. }
    26. }
    27. //Load events from server to display on caledar
    28. function populate() {
    29. clearCalendar();
    30. $http.get('/home/getevents', {
    31. cache: false,
    32. params: {}
    33. }).then(function (data) {
    34. $scope.events.slice(0, $scope.events.length);
    35. angular.forEach(data.data, function (value) {
    36. $scope.events.push({
    37. id : value.EventID,
    38. title: value.Title,
    39. description: value.Description,
    40. start: new Date(parseInt(value.StartAt.substr(6))),
    41. end: new Date(parseInt(value.EndAt.substr(6))),
    42. allDay: value.IsFullDay,
    43. stick: true
    44. });
    45. });
    46. });
    47. }
    48. populate();
    49. //UI- calendar configuration
    50. $scope.uiConfig = {
    51. calendar: {
    52. height: 450,
    53. editable: true,
    54. displayEventTime: true,
    55. header: {
    56. left: 'month,agendaWeek,agendaDay',
    57. center: 'title',
    58. right:'today prev,next'
    59. },
    60. timeFormat : {
    61. month : ' ', // for hide on month view
    62. agenda: 'h:mm t'
    63. },
    64. selectable: true,
    65. selectHelper: true,
    66. select : function(start, end){
    67. var fromDate = moment(start).format('YYYY/MM/DD LT');
    68. var endDate = moment(end).format('YYYY/MM/DD LT');
    69. $scope.NewEvent = {
    70. EventID : 0,
    71. StartAt : fromDate,
    72. EndAt : endDate,
    73. IsFullDay :false,
    74. Title : '',
    75. Description : ''
    76. }
    77. $scope.ShowModal();
    78. },
    79. eventClick: function (event) {
    80. $scope.SelectedEvent = event;
    81. var fromDate = moment(event.start).format('YYYY/MM/DD LT');
    82. var endDate = moment(event.end).format('YYYY/MM/DD LT');
    83. $scope.NewEvent = {
    84. EventID : event.id,
    85. StartAt : fromDate,
    86. EndAt : endDate,
    87. IsFullDay :false,
    88. Title : event.title,
    89. Description : event.description
    90. }
    91. $scope.ShowModal();
    92. },
    93. eventAfterAllRender: function () {
    94. if ($scope.events.length > 0 && isFirstTime) {
    95. uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
    96. isFirstTime = false;
    97. }
    98. }
    99. }
    100. };
    101. //This function shows bootstrap modal dialog
    102. $scope.ShowModal = function () {
    103. $scope.option = {
    104. templateUrl: 'modalContent.html',
    105. controller: 'modalController',
    106. backdrop: 'static',
    107. resolve: {
    108. NewEvent: function () {
    109. return $scope.NewEvent;
    110. }
    111. }
    112. };
    113. //CRUD operations on Calendar starts here
    114. var modal = $uibModal.open($scope.option);
    115. modal.result.then(function (data) {
    116. $scope.NewEvent = data.event;
    117. switch (data.operation) {
    118. case 'Save': //save
    119. $http({
    120. method: 'POST',
    121. url: '/home/SaveEvent',
    122. data : $scope.NewEvent
    123. }).then(function (response) {
    124. if (response.data.status) {
    125. populate();
    126. }
    127. })
    128. break;
    129. case 'Delete': //delete
    130. $http({
    131. method: 'POST',
    132. url: '/home/DeleteEvent',
    133. data: {'eventID' : $scope.NewEvent.EventID }
    134. }).then(function (response) {
    135. if (response.data.status) {
    136. populate();
    137. }
    138. })
    139. break;
    140. default:
    141. break;
    142. }
    143. }, function () {
    144. console.log('Modal dialog closed');
    145. })
    146. }
    147. }])
  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.