@model IEnumerable<NewReminderASP.Domain.Entities.EventViewModel>

@{
    ViewData["Title"] = "Calendar";
    var eventsJson = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Select(e => new
    {
        id = e.ID.ToString(),
        title = e.Title,
        start = e.StartDate,
        userID = e.UserID,
        login = e.Login,
        eventTypes = e.EventTypes

    }));
}

<div id="calendar"></div>
<div id="external-events">
    <p><strong>Draggable Events</strong></p>
    <div class='fc-event'>My Event 1</div>
    <div class='fc-event'>My Event 2</div>
</div>

<style>
    .fc-header {
        background-color: #3498db;
        color: #fff;
        padding: 10px;
    }

    .fc-body {
        background-color: #fff;
        padding: 10px;
    }

    .fc-cell {
        border: 1px solid #ccc;
        padding: 5px;
    }

    .fc-event {
        background-color: #2ecc71;
        color: #fff;
        border: none;
        padding: 5px;
        cursor: pointer;
    }

        .fc-event:hover {
            background-color: #27ae60;
        }
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.13/main.min.css">
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.13/index.global.min.js'></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // External events setup
    var containerEl = document.getElementById('external-events');
    new FullCalendar.Draggable(containerEl, {
        itemSelector: '.fc-event'
    });

    var calendarEl = document.getElementById('calendar');
    var calendarEvents = JSON.parse('@Html.Raw(eventsJson)');

    var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        events: calendarEvents,
        editable: true, // Enable dragging and resizing
        droppable: true, // Allow events to be dropped
        dateClick: function (info) {
            var selectedDate = info.dateStr; // Get the selected date from the calendar
            var createUrl = '@Url.Action("Create", "Event", new { area = "EventsArea" })'; // Form the URL for creating a new event
            createUrl = createUrl + '?selectedDate=' + selectedDate; // Add the selected date to the URL
            window.location.href = createUrl; // Navigate to the event creation page with the selected date
        },
        eventClick: function(info) {
            var eventId = info.event.id;
            var detailsUrl = '@Url.Action("EventDetails", "Event", new { area = "EventsArea" })' + '/' + eventId; // Form the URL for event details
            window.location.href = detailsUrl; // Navigate to the event details page
        },
        eventReceive: function(info) {
            // Handle the event when it is received from an external drag source
            var event = info.event;
            $.ajax({
                url: '@Url.Action("Create", "Event", new { area = "EventsArea" })',
                type: 'POST',
                data: {
                    title: event.title,
                    start: event.start,
                    userID: event.extendedProps.userID,
                    login: event.extendedProps.login,
                    eventTypes: event.extendedProps.eventTypes
                },
                success: function (response) {
                    alert('Event saved successfully');
                },
                error: function (xhr, status, error) {
                    alert('Failed to save event');
                    event.remove(); // Remove the event from calendar if not saved
                }
            });
        },
        eventDrop: function(info) {
            // Handle after an event is dropped
            var event = info.event;
            $.ajax({
                url: '@Url.Action("Edit", "Event", new { area = "EventsArea" })',
                type: 'POST',
                data: {
                    id: event.id,
                    title: event.title,
                    start: event.start,
                    userID: event.extendedProps.userID,
                    login: event.extendedProps.login,
                    eventTypes: event.extendedProps.eventTypes
                },
                success: function (response) {
                    alert('Event updated successfully');
                },
                error: function (xhr, status, error) {
                    alert('Failed to update event');
                    info.revert(); // Revert the event to its original position
                }
            });
        },
        eventResize: function(info) {
            // Handle after an event is resized
            var event = info.event;
            $.ajax({
                url: '@Url.Action("Edit", "Event", new { area = "EventsArea" })',
                type: 'POST',
                data: {
                    id: event.id,
                    title: event.title,
                    start: event.start,
                    end: event.end,
                    userID: event.extendedProps.userID,
                    login: event.extendedProps.login,
                    eventTypes: event.extendedProps.eventTypes
                },
                success: function (response) {
                    alert('Event resized successfully');
                },
                error: function (xhr, status, error) {
                    alert('Failed to resize event');
                    info.revert(); // Revert the event to its original size
                }
            });
        }
    });

    calendar.render();
});
</script>


  public ActionResult Calendar()
  {
      var events = _provider.GetEvents().Select(e => new EventViewModel(e)).ToList();
      return View(events);
  }

  using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace NewReminderASP.Domain.Entities
{
    public class Event
    {
        public int ID { get; set; }

        public int UserID { get; set; }

        public int EventTypeID { get; set; }

        [Required(ErrorMessage = "Please select a Title")]
        public string Title { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

        public DateTime Date { get; set; } 

        public TimeSpan Time { get; set; }  

        public int RecurrenceID { get; set; }

        [Required(ErrorMessage = "Please select a Reminder")]
        public string Reminders { get; set; }

        public User User { get; set; }


        public string Recurrence { get; set; }
        public string EventTypes { get; set; }
        public string Login { get; set; }
        public List<User> Users { get; set; }
        public List<EventType> EventsTypes { get; set; }
        public List<EventRecurrence> EventRecurrences { get; set; }



        public string StartDate { get; set; }

        
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;

namespace NewReminderASP.Domain.Entities
{
    public class EventViewModel
    {

        public int ID { get; set; }

        public int UserID { get; set; }

        public int EventTypeID { get; set; }

        [Required(ErrorMessage = "Please select a Title")]
        public string Title { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

        public DateTime Date { get; set; }

        public TimeSpan Time { get; set; }

        public int RecurrenceID { get; set; }

        [Required(ErrorMessage = "Please select a Reminder")]
        public string Reminders { get; set; }

        public User User { get; set; }


        public string Recurrence { get; set; }
        public string EventTypes { get; set; }
        public string Login { get; set; }
        public List<User> Users { get; set; }
        public List<EventType> EventsTypes { get; set; }
        public List<EventRecurrence> EventRecurrences { get; set; }



        public string StartDate { get; set; }
        public string EndDate { get; set; }


        public EventViewModel(Event e)
        {
            ID = e.ID;
            Title = e.Title;
            StartDate = string.Format("{0}T{1}", e.Date.ToString("yyyy-MM-dd"), e.Time.ToString("hh\\:mm\\:ss"));
            UserID = e.UserID;
            Login = e.Login;
            EventTypes = e.EventTypes;
        }
    }
}

 [Authorize]
 public ActionResult Index(string orderBy, string sortOrder, int page = 1)
 {
     var events = _provider.GetEvents().AsQueryable();
     const int pageSize = 10;

     var paginatEdevents = DynamicSortAndPaginate(events, orderBy, sortOrder, page, pageSize).ToList();


     var totalEvents = events.Count();
     var totalPages = (int)Math.Ceiling((double)totalEvents / pageSize);

     ViewBag.OrderBy = orderBy;
     ViewBag.SortOrder = sortOrder;
     ViewBag.CurrentPage = page;
     ViewBag.TotalPages = totalPages;

     return View(paginatEdevents);
 }

 [Authorize]
public ActionResult Edit(int id)
{
    var model = _provider.GetEvent(id);
    if (model == null || (!User.IsInRole("Admin") && model.Login != User.Identity.Name))
        return new HttpUnauthorizedResult();

    model.Users = _userProvider.GetUsers();
    model.EventsTypes = _provider.GetEventTypes();
    model.EventRecurrences = _provider.GetEventRecurrences();

    return View(model);
}

 [Authorize]
 [HttpPost]
 public ActionResult Edit(Event events)
 {
     if (ModelState.IsValid)
     {
         var existingEvent = _provider.GetEvent(events.ID);
         if (existingEvent != null && (User.IsInRole("Admin") || existingEvent.Login == User.Identity.Name))
         {
             _provider.UpdateEvent(events);
             if (User.IsInRole("Admin"))
             {
                 return RedirectToAction("Index");
             }
             else
             {
                 return RedirectToAction("Details", "Event", new { area = "EventsArea", userName = User.Identity.Name });
             }
         }

         return new HttpUnauthorizedResult();
     }

     events.Users = _userProvider.GetUsers();
     events.EventsTypes = _provider.GetEventTypes();
     events.EventRecurrences = _provider.GetEventRecurrences();
     return View(events);
 }

  [Authorize]
 public ActionResult EventDetails(int id)
 {
     var events = _provider.GetEvent(id);


     if (events == null) return HttpNotFound();


     if (User.IsInRole("Admin") || events.Login == User.Identity.Name)
         return View(events);
     return new HttpUnauthorizedResult();
 }


        [Authorize]
        public ActionResult Create()
        {
            var model = new Event();
            model.Users = _userProvider.GetUsers();
            model.EventsTypes = _provider.GetEventTypes();
            model.EventRecurrences = _provider.GetEventRecurrences();


            return View(model);
        }

        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Event events)
        {
            if (ModelState.IsValid)
            {
                _provider.AddEvent(events);
                if (User.IsInRole("Admin"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return RedirectToAction("Details", "Event", new { area = "EventsArea", userName = User.Identity.Name });
                }
            }


            events.Users = _userProvider.GetUsers();
            events.EventsTypes = _provider.GetEventTypes();
            events.EventRecurrences = _provider.GetEventRecurrences();


            return View(events);
        }

        [HttpPost]
        public ActionResult SaveSelectedDate(string selectedDate)
        {
            // Логика сохранения выбранной даты на сервере
            // Пример сохранения данных в базе данных или выполнения дополнительных операций

            // Возвращение ответа клиенту после сохранения
            return Json(new { success = true });
        }

         [Authorize]
 public ActionResult Delete(int id)
 {
     var events = _provider.GetEvent(id);


     if (events == null || (!User.IsInRole("Admin") && events.Login != User.Identity.Name))
         return new HttpUnauthorizedResult();

     return View(events);
 }

 [Authorize]
 [HttpPost]
 [ActionName("Delete")]
 [ValidateAntiForgeryToken]
 public ActionResult DeleteConfirmed(int id)
 {
     var events = _provider.GetEvent(id);


     if (events == null || (!User.IsInRole("Admin") && events.Login != User.Identity.Name))
         return new HttpUnauthorizedResult();

     _provider.DeleteEvent(id);
     if (User.IsInRole("Admin"))
     {
         return RedirectToAction("Index");
     }
     else
     {
         return RedirectToAction("Details", "Event", new { area = "EventsArea", userName = User.Identity.Name });
     }
 }

 Есть это нужно настроить календарь чтобы можно было создавать смотреть детали редактировать и удалять события возможно делая переадресацию на метода контролера возможно и в самом календаре как это лучше реализовать чтобы все было красиво и удобно помоги пожалуйста