search envelope-o feed check
Home Unanswered Active Tags New Question
user comment-o

Send the list of all the created events to the controller.

Asked by Candide
4 years ago.

Please i need your help. I am using DayPilot Pro for ASP.NET MVC.

I want to send the list of all the created events to the controller.
I want to submit the form with these events.

my view

<form action="/Shift/Create" method="post" enctype="multipart/form-data">
   

    <h4 style="background-color: #5a3055; margin-bottom: 20px;color: white;">Identification du shift</h4>

    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-default">
                <div class="panel-body">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Nom, new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            @Html.EditorFor(model => model.Nom, new { htmlAttributes = new { @class = "input-sm form-control" } })
                            @Html.ValidationMessageFor(model => model.Nom, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.DateDeDebut, new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            <div class='input-group date' id='DateDeDebut'>
                                <input type='text' class="input-sm form-control input-sm" name='DateDeDebut' id='DateDeDebut' required />
                                <span class="input-group-addon">
                                    <i class="fa fa-calendar" aria-hidden="true"></i>
                                </span>
                            </div>
                            @Html.ValidationMessageFor(model => model.DateDeDebut, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-9 col-md-offset-3">
                            <label>@Html.EditorFor(model => model.ShiftParDefaut) Considérer comme le shift par défaut</label>
                            @Html.ValidationMessageFor(model => model.ShiftParDefaut, "", new { @class = "text-danger" })
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <br />
    <h4 style="background-color: #5a3055; margin-bottom: 20px;color: white;">Configuration</h4>
    <br />
    <div class="left-column">

        @Html.DayPilotNavigator("dpn", new DayPilotNavigatorConfig
        {
         ShowMonths = 5,
         SkipMonths = 5,
         ShowWeekNumbers = true,
         BoundDayPilot = "dp",
         SelectMode = NavigatorSelectMode.Week,

         //TimeRangeSelectedHandling = TimeRangeSelectedHandlingType.JavaScript ,

         //TimeRangeSelectedJavaScript  = "changeStartDate()"

         //VisibleRangeChangedHandling = VisibleRangeChangedHandlingType.

          })
    </div>


    <div class="right-column">

        @Html.DayPilotMenu("menu", new DayPilotMenuConfig
        {
          Items = new DayPilot.Web.Mvc.MenuItemCollection
          {
            new DayPilot.Web.Mvc.MenuItem { Text = "Open", Action = MenuItemAction.JavaScript, JavaScript = "alert(e.value());"},

            new DayPilot.Web.Mvc.MenuItem { Text = "Copy", Action = MenuItemAction.JavaScript, JavaScript = "copied = e.value();"}
          }
        })

        @Html.DayPilotMenu("menu_selection", new DayPilotMenuConfig
        {
          Items = new DayPilot.Web.Mvc.MenuItemCollection
          {
            new DayPilot.Web.Mvc.MenuItem { Text = "Paste", Action = MenuItemAction.JavaScript, JavaScript = "if (!copied) { alert('You need to copy an event first.'); return; } dpc.commandCallBack('paste', {id:copied, start: e.start});"}
          }
        })


        @*<div class="space">
            Semaine:
            <a href="javascript:dpc.commandCallBack("previous");" class="btn btn-primary btn-xs">Precédente</a>
            |
            <a href="javascript:dpc.commandCallBack("next");" class="btn btn-info btn-xs">Suivante</a>
        </div>*@

        @*@if (actionName == "Create")
        {
           
        }
        else
        {
           
        }*@

        @Html.DayPilotCalendar("dp", new DayPilotCalendarConfig
        {
           // BackendUrl = Url.Action("Backend", "Calendar"),
            BackendUrl = Url.Action("Backend", "Shift"),
            ViewType = ViewType.Week,
            TimeRangeSelectedHandling = TimeRangeSelectedHandlingType.JavaScript,
            TimeRangeSelectedJavaScript = "create(start, end)",
            EventClickHandling = EventClickHandlingType.JavaScript,
            EventClickJavaScript = "edit(e)",
            EventMoveHandling = EventMoveHandlingType.Notify,
            EventResizeHandling = EventResizeHandlingType.Notify,
            EventDeleteHandling = EventDeleteHandlingType.CallBack,

            ContextMenu = "menu",
            //EventMoveJavaScript = "dpc.eventMoveCallBack(e, newStart, newEnd, newResource, {ctrl: ctrl, shift: shift} )",
            ContextMenuSelection = "menu_selection",
            UseEventBoxes = UseBoxes.ShortEventsOnly,
            Height = 400,
            BusinessBeginsHour = 0,
            BusinessEndsHour = 20,
            DayBeginsHour = 6, // pour les shifts de nuit
            DayEndsHour = 6,   // pour les shifts de nuit
           // HeightSpec = HeightSpec.Full,
            HeightSpec = HeightSpec.BusinessHours,
            //Theme = "calendar_green"
            Theme = "calendar_blue"

        })
    </div>

    <br />

    <div class="form-group">
        <div class="col-md-offset-3 col-md-9">
            <input type="submit" value="Créer le shift" class="btn btn-primary btn-sm" />
        </div>
    </div>

 </form>

 <script type="text/javascript">

    function create(start, end) {
        var m = new DayPilot.Modal();
         //m.top = 60;
         //m.width = 300;
         //m.opacity = 70;
         m.border = "10px solid #d0d0d0";

       
        m.showUrl('@Url.Action("Create", "Event")?start=' + start + '&end=' + end);

       

         m.closed = function () {
            if (this.result == "OK") {
                dp.commandCallBack('refresh');
                
            }
            dp.clearSelection();
        };

        //dp.events.add(e).notify();
        //dp.queue.notify();

    }

    function edit(e) {
        var m = new DayPilot.Modal();
         m.border = "10px solid #d0d0d0";
        
        m.showUrl('@Url.Action("Edit", "Event")/' + e.id());


         //dp.commandCallBack('refresh');

        m.closed = function () {
            if (this.result == "OK") {
                dp.commandCallBack('refresh');
            }
            dp.clearSelection();
        };

        //dp.events.update(e).notify(); // to put event in queue and notify server
    }

    function changeStartDate() {

        dp.startDate = dm.startDate;

        dp.update();

        dp.events.load("/api/events");
    }

    $('#DateDeDebut').datetimepicker({
        //    defaultDate: moment(),
        format: 'DD/MM/YYYY',
        locale: 'fr'

    }).on('dp.change', function(e) {


        var datededebut = $('#DateDeDebut').data('DateTimePicker').date();

        dpc.startDate = "2013-07-31";
        dpc.update();

        dpc.events.load("/api/events");

    });

    </script>

my controller

[Authorize]
    [RoutePrefix("Shift")]
    public class ShiftController : Controller
    {
        IMSWEBContext db = new IMSWEBContext();

        IShiftService _shiftService;
        IMapper _mapper;

        public ShiftController(
            //IErrorService errorService,
            IShiftService shiftService,
            IMapper mapper)
            //: base(errorService)
        {
            _shiftService = shiftService;
            _mapper = mapper;

        }

        public ActionResult Backend()
        {
            return new Dpc().CallBack(this);
        }



        [HttpGet]
        [Authorize]
        [Route("index")]
        public async Task<ActionResult> Index()
        {
            var shiftsAsync = _shiftService.GetAllShiftAsync();
            var vmodel = _mapper.Map<Shift>, IEnumerable<GetShiftViewModel>>(await shiftsAsync);
            return View(vmodel);
        }

        [HttpGet]
        [Authorize]
        [Route("create")]
        public ActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Create(GetShiftViewModel shift)
        {
            if (!ModelState.IsValid)
                return View(shift);

            if (shift != null)
            {
                var newShift = _mapper.Map<GetShiftViewModel, Shift>(shift);


                if (newShift.ShiftParDefaut == 1)
                {
                    var setShifts = _shiftService.GetAllShift().Where(x => x.Id != newShift.Id);

                    if (setShifts != null)
                    {
                        foreach (Shift givenshift in setShifts)
                        {
                            givenshift.ShiftParDefaut = 0;
                            _shiftService.UpdateShift(givenshift);
                        }
                    }

                }

                _shiftService.AddShift(newShift);
                _shiftService.SaveShift();

                int newshiftId = newShift.Id;

                //dpc
                List<EventInfo> setOfActiveEvents = new Dpc().SelectedEvents;
               // List<EventInfo> setOfActiveEvents = new Dpc().Events;

                var listOfShiftEventsToInsert = new List<ShiftsDetail>(); //you creating list of your entities
                foreach (EventInfo givenevent in setOfActiveEvents)
                {
                    listOfShiftEventsToInsert.Add(new ShiftsDetail
                    {
                        shift_id = newshiftId,
                        timetable_id = int.Parse(givenevent.Id),
                        DateDuJour = givenevent.Start.Date,
                        
                    }); //here you create your entity and add it to List
                };
                db.shiftsDetails.AddRange(listOfShiftEventsToInsert); //here you add all new entities to context
                db.SaveChanges();

                AddToastMessage("", "Le shift a été créée avec succès.", ToastType.Success);
                return RedirectToAction("Create");
            }
            else
            {
                AddToastMessage("", "Aune donnée relative à la création d'un shift n'a pu être trouvée.", ToastType.Error);
                return RedirectToAction("Create");
            }
            
        }


        [HttpGet]
        [Authorize]
        [Route("delete/{id}")]
        public ActionResult Delete(int id)
        {
            _shiftService.DeleteShift(id);
            _shiftService.SaveShift();
            AddToastMessage("", "Le shift été supprimé avec succès.", ToastType.Success);
            return RedirectToAction("Index");
        }

        public void AddToastMessage(string title, string message, ToastType toastType = ToastType.Info)
        {
            Toastr toastr = TempData["Toastr"] as Toastr;
            toastr = toastr ?? new Toastr();
            toastr.AddToastMessage(title, message, toastType);
            TempData["Toastr"] = toastr;
        }


        class Dpc : DayPilotCalendar
        {
            CalendarDataContext dc = new CalendarDataContext();

            protected override void OnInit(InitArgs e)
            {
                UpdateWithMessage("Contruisez votre shift!", CallBackUpdateType.Full);
                //String value = getClientState().getJSONObject("container").getString("value"); // test
            }

            protected override void OnCommand(CommandArgs e)
            {
                switch (e.Command)
                {
                    // en cas de rafraichissement de la page

                    case "refresh":
                        Update();
                        break;

                    // En cas de copier/coller

                    case "paste":
                        DateTime pasteHere = (DateTime)e.Data["start"];
                        string id = (string)e.Data["id"];

                        // 1. trouve l'event en utilisant l'id
                        // 2. cree un nouvel enregistrement dans la base en utilisant les propriétés de l'event original
                        // 3. Charge l'event dans l'ensemble des events

                        var record = (from ev in dc.Events where ev.Id == int.Parse(id) select ev).First();

                        var toBeCreated = new Event()
                        {
                            Start = record.Start,
                            End = record.End,
                            Text = record.Text,
                            color = record.color,
                            eventType = record.eventType
                        };
                        dc.Events.InsertOnSubmit(toBeCreated);
                        dc.SubmitChanges();


                        UpdateWithMessage("Plage horaire copiée.");
                        break;

                    case "navigate":
                        StartDate = (DateTime)e.Data["start"];
                        Update(CallBackUpdateType.Full);
                        break;

                    case "previous":
                        StartDate = StartDate.AddDays(-7);
                        Update(CallBackUpdateType.Full);
                        break;
                    case "next":
                        StartDate = StartDate.AddDays(7);
                        Update(CallBackUpdateType.Full);
                        break;
                }
            }

            protected override void OnEventMove(EventMoveArgs e)
            {
                var item = (from ev in dc.Events where ev.Id == Convert.ToInt32(e.Id) select ev).First();
                if (item != null)
                {
                    item.Start = e.NewStart;
                    item.End = e.NewEnd;
                    dc.SubmitChanges();
                }
            }

            protected override void OnEventResize(EventResizeArgs e)
            {
                var item = (from ev in dc.Events where ev.Id == Convert.ToInt32(e.Id) select ev).First();
                if (item != null)
                {
                    item.Start = e.NewStart;
                    item.End = e.NewEnd;
                    dc.SubmitChanges();
                }
            }
            //protected virtual void OnEventEdit(EventEditArgs e)
            //{
            //    Update();
            //}

            protected override void OnEventDelete(EventDeleteArgs e)
            {
                var item = (from ev in dc.Events where ev.Id == Convert.ToInt32(e.Id) select ev).First();
                dc.Events.DeleteOnSubmit(item);
                dc.SubmitChanges();
                Update();
            }

            protected override void OnFinish()
            {
                // only load the data if an update was requested by an Update() call

                if (UpdateType == CallBackUpdateType.None)
                {
                    return;
                }

                DataIdField = "Id";
                DataStartField = "Start";
                DataEndField = "End";
                DataTextField = "Text";

                //  Events = new EventManager(Controller).Data.AsEnumerable();

                Events = from e in dc.Events where !((e.End <= VisibleStart) || (e.Start >= VisibleEnd)) select e;
            }

            // Pour ajouter une couleur pour chaque plage horaire

            protected override void OnBeforeEventRender(BeforeEventRenderArgs e)
            {

                // Cela suppose que l'objet event dans la collection d'events possède une propriété ou un champ "color"
                e.BackgroundColor = (string)e.DataItem["color"];
               // e.Start = e.DataItem["Start"];


            }


            // Mettre tous les évènements dans une file d'attente afin de les
            // envoyer de façon groupée au serveur suite à une notification dépuis
            // la vue

            protected override void OnNotify(NotifyArgs e)
            {
                foreach (DayPilotArgs a in e.Queue)
                {
                    if (a is EventUpdateArgs)
                    {
                        EventUpdateArgs updateArgs = (EventUpdateArgs)a;
                        string id = updateArgs.Event.Id;
                        string newText = updateArgs.New.Text;
                        // update the db
                    }
                }
            }

            // copier/coller d'un event


        }

    }
Answer posted by Dan Letecky [DayPilot]
4 years ago.

Submitting changes using a form is not a supported scenario. However, you can use the built-in queue to submit all changes at once using a CallBack.

When creating, updating or deleting the event using the events API, call queue() on the action to store the change in the queue. Then you can send the queue at once by calling queue.notify() [https://api.daypilot.org/daypilot-scheduler-queue-notify/].

Example for creating a new event:

dp.events.add(e).queue();
dp.queue.notify();

This will fire the OnNotify event handler on the server side with the queue items.

This question is more than 1 months old and has been closed. Please create a new question if you have anything to add.